let possibleString: String? = "An optional string." let forcedString: String = possibleString! // 需要惊叹号来获取值
打印输出
使用 print 打印内容
1 2 3 4
let foo = "Hello World" print(foo) // 可以直接在字符串中嵌入变量 print("The current value is \(foo)")
条件语句
if
1 2 3 4 5 6 7 8 9 10 11
// 布尔类型 let orangesAreOrange = true let turnipsAreDelicious = false
if turnipsAreDelicious { print("Mmm, tasty turnips!") } elseif orangesAreOrange { print("Eww, turnips are horrible.") } else { print("Nothing") }
如果在需要使用 Bool 类型的地方使用了非布尔值,会报错
1 2 3 4
let i = 1 if i { // 这里会报错 }
Switch
匹配的 case 分支中的代码执行完毕后,程序会终止switch语句,而不会继续执行下一个 case 分支。这也就是说,不需要在 case 分支中显式地使用break语句
1 2 3 4 5 6 7 8 9
let someCharacter: Character = "z" switch someCharacter { case"a": print("The first letter of the alphabet") case"z": print("The last letter of the alphabet") default: print("Some other character") }
case 分支的模式也可以是一个值的区间
1 2 3 4 5 6 7 8 9 10 11 12
let approximateCount = 62 var naturalCount: String switch approximateCount { case0: naturalCount = "no" case1..<5: naturalCount = "a few" case5..<12: naturalCount = "several" default: naturalCount = "many" }
Where
case 分支的模式可以使用where语句来判断额外的条件。
1 2 3 4 5 6 7 8 9
let yetAnotherPoint = (1, -1) switch yetAnotherPoint { caselet (x, y) where x == y: print("(\(x), \(y)) is on the line x == y") caselet (x, y) where x == -y: print("(\(x), \(y)) is on the line x == -y") caselet (x, y): print("(\(x), \(y)) is just some arbitrary point") }
let someCharacter: Character = "e" switch someCharacter { case"a", "e", "i", "o", "u": print("\(someCharacter) is a vowel") case"b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z": print("\(someCharacter) is a consonant") default: print("\(someCharacter) is not a vowel or a consonant") }
// 10到1,步长为1 for i in (1...10).reversed() { print(i) }
// 0到10,不包含10,步长为2 for i instride(from: 0, to: 10, by: 2) { print(i) }
// 0到10,包含10,步长为2 for i instride(from: 0, through: 10, by: 2) { print(i) }
// 0.5到10,包含10,步长为2.5 for i instride(from: 0.5, through: 10, by: 2.5) { print(i) }
while 循环
1 2 3
while condition { statements }
Repeat-While
1 2 3
repeat { statements } while condition
控制转移语句
控制转移语句改变你代码的执行顺序,通过它可以实现代码的跳转。Swift 有五种控制转移语句:
continue
break
fallthrough 贯穿
return
throw 抛出异常
如果需要让 Switch 的语法具有 C 风格的贯穿的特性,可以在每个需要该特性的 case 分支中使用fallthrough关键字。下面的例子使用fallthrough来创建一个数字的描述语句。
1 2 3 4 5 6 7 8 9 10 11
let integerToDescribe = 5 var description = "The number \(integerToDescribe) is" switch integerToDescribe { case2, 3, 5, 7, 11, 13, 17, 19: description += " a prime number, and also" fallthrough default: description += " an integer." } // 输出 "The number 5 is a prime number, and also an integer." print(description)
字符串
字符串用双引号
1
let someString = "Some string literal value"
初始化空字符串
1 2 3
var emptyString = ""// 空字符串字面量 var anotherEmptyString = String() // 初始化方法 // 两个字符串均为空并等价
可通过for-in循环来遍历字符串中的characters属性来获取每一个字符的值:
1 2 3
for character in"Dog!".characters { print(character) }