编程基础/变量示例 Swift
外观
< 编程基础
以下示例演示了 Swift 中的数据类型、算术运算和输入。
// This program demonstrates variables, literal constants, and data types.
var i: Int
var d: Double
var s: String
var b: Bool
i = 1234567890
d = 1.23456789012345
s = "string"
b = true
print("Integer i =", i)
print("Double d =", d)
print("String s =", s)
print("Boolean b =", b)
Integer i = 1234567890 Double d = 1.23456789012345 String s = string Boolean b = true
每个代码元素代表
//
开始一个注释var i: Int
定义一个名为 i 的整型变量var d: Double
定义一个名为 d 的双精度浮点型变量var s: String
定义一个名为 s 的字符串变量var b: Bool
定义一个名为 b 的布尔型变量i = , d = , s =, b =
将字面值赋给相应的变量print()
调用 print 函数
// This program demonstrates arithmetic operations.
var a: Int
var b: Int
a = 3
b = 2
print("a =", a)
print("b =", b)
print("a + b =", (a + b))
print("a - b =", (a - b))
print("a * b =", a * b)
print("a / b =", a / b)
print("a % b =", (a % b))
a = 3 b = 2 a + b = 5 a - b = 1 a * b = 6 a / b = 1 a % b = 1
每个新的代码元素代表
+, -, *, /, and %
分别代表加法、减法、乘法、除法和取模。
// This program converts a Fahrenheit temperature to Celsius.
//
// References:
// https://www.mathsisfun.com/temperature-conversion.html
// https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html
var fahrenheit: Double
var celsius: Double
print("Enter Fahrenheit temperature:")
fahrenheit = Double(readLine()!)!
celsius = (fahrenheit - 32) * 5 / 9
print(String(fahrenheit) + "° Fahrenheit is " + String(celsius) + "° Celsius")
Enter Fahrenheit temperature: 100 100.0° Fahrenheit is 37.7777777777778° Celsius
每个新的代码元素代表
readline()!
从标准输入读取下一行Double()!
将输入转换为双精度浮点型值String()
将输出数值转换为字符串