// 构造语法来创建一个由特定数据类型构成的空数组
var someInts = [Int]()
// threeDoubles 是一种 [Double] 数组,等价于 [0.0, 0.0, 0.0]
var threeDoubles = Array(repeating: 0.0, count: 3)
// threeDoubles,threeDoublest [Int]() 可以直接相加
var sixDoubles = threeDoubles + threeDoubles
// 字面量
var shoppingList: [String] = ["Eggs", "Milk"]
// 添加元素
shoppingList.append("Flour")
// 使用 += 添加元素
shoppingList += ["Baking Powder"]
// 使用下标, 同ObjC, 下标可以是个范围 例如: shoppingList[4...6]
shoppingList[0] = "Six eggs"
// 如果同时需要每个数据项的值和索引值,可以使用 enumerated() 方法来进行数组遍历
for (index, value) in shoppingList.enumerated() {
print("Item \(String(index + 1)): \(value)")
}
一个字典的 Key
类型必须遵循 Hashable
协议
// 构造一个字典
var namesOfIntegers = [Int: String]()
// 字面量
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
// 取值赋值
airports["LHR"] = "London Heathrow"
// updateValue(_:forKey:) 这个方法返回更新值之前的原值。这样使得你可以检查更新是否成功。
// // 输出“The old value for DUB was London Heathrow.”
if let oldValue = airports.updateValue("Dublin Airport", forKey: "LHR") {
print("The old value for DUB was \(oldValue).")
}
let approximateCount = 62
let countedThings = "moons orbiting Saturn"
let naturalCount: String
switch approximateCount {
case 0:
naturalCount = "no"
case 1..<5:
naturalCount = "a few"
case 5..<12:
naturalCount = "several"
case 12..<100:
naturalCount = "dozens of"
case 100..<1000:
naturalCount = "hundreds of"
default:
naturalCount = "many"
}
我们可以使用元组在同一个 switch
语句中测试多个值。元组中的元素可以是值,也可以是区间。另外,使用下划线(_
)来匹配所有可能的值。
let somePoint = (1, 1)
switch somePoint {
case (0, 0):
print("\(somePoint) is at the origin")
case (_, 0):
print("\(somePoint) is on the x-axis")
case (0, _):
print("\(somePoint) is on the y-axis")
case (-2...2, -2...2):
print("\(somePoint) is inside the box")
default:
print("\(somePoint) is outside of the box")
}
// 输出“(1, 1) is inside the box”
case 分支允许将匹配的值声明为临时常量或变量,并且在 case 分支体内使用 —— 这种行为被称为值绑定(value binding),因为匹配的值在 case 分支体内,与临时的常量或变量绑定。
let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
print("on the x-axis with an x value of \(x)")
case (0, let y):
print("on the y-axis with a y value of \(y)")
case let (x, y):
print("somewhere else at (\(x), \(y))")
}
// 输出“on the x-axis with an x value of 2”
case 分支的模式可以使用 where
语句来判断额外的条件。
let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y:
print("(\(x), \(y)) is on the line x == y")
case let (x, y) where x == -y:
print("(\(x), \(y)) is on the line x == -y")
case let (x, y):
print("(\(x), \(y)) is just some arbitrary point")
}
// 输出“(1, -1) is on the line x == -y”
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")
}
// 输出“e is a vowel”
continue
语句告诉一个循环体立刻停止本次循环,重新开始下次循环break
语句会立刻结束整个控制流的执行在 Swift 里,switch
语句不会从上一个 case 分支跳转到下一个 case 分支中。相反,只要第一个匹配到的 case 分支完成了它需要执行的语句,整个 switch
代码块完成了它的执行。相比之下,C 语言要求你显式地插入 break
语句到每个 case 分支的末尾来阻止自动落入到下一个 case 分支中。Swift 的这种避免默认落入到下一个分支中的特性意味着它的 switch
功能要比 C 语言的更加清晰和可预测,可以避免无意识地执行多个 case 分支从而引发的错误。
如果你确实需要 C 风格的贯穿的特性,你可以在每个需要该特性的 case 分支中使用 fallthrough
关键字。下面的例子使用 fallthrough
来创建一个数字的描述语句。
let integerToDescribe = 5
var description = "The number \(integerToDescribe) is"
switch integerToDescribe {
case 2, 3, 5, 7, 11, 13, 17, 19:
description += " a prime number, and also"
fallthrough
default:
description += " an integer."
}
print(description)
// 输出“The number 5 is a prime number, and also an integer.”
像 if
语句一样,guard
的执行取决于一个表达式的布尔值。我们可以使用 guard
语句来要求条件必须为真时,以执行 guard
语句后的代码。不同于 if
语句,一个 guard
语句总是有一个 else
从句,如果条件不为真则执行 else
从句中的代码。
override func viewDidLoad() {
super.viewDidLoad()
let person: [String: String] = ["name": "summerxx"]
self.greet(person: person)
}
func greet(person: [String: String]) {
guard let name = person["name"] else {
return
}
print("Hello \(name)!")
guard let location = person["location"] else {
print("I hope the weather is nice near you.")
return
}
print("I hope the weather is nice in \(location).")
}
Hello summerxx!
I hope the weather is nice near you.
print(self.arithmeticMean(1, 2, 3, 4, 5))
print(self.printStr("summerxx's", " blog", " is", " summerxx.com"))
func arithmeticMean(_ numbers: Double...) -> Double {
var total: Double = 0
for number in numbers {
total += number
}
return total / Double(numbers.count)
}
func printStr(_ strs: String...) -> String {
var sumStr: String = ""
for (index, str) in strs.enumerated() {
print(index)
sumStr += str
}
return sumStr
}
/*
3.0
summerxx's blog is summerxx.com
*/
self.printMathResult({ (a, b) -> Int in
return a * b
}, 3, 4)
func printMathResult(_ mathFunction: (_ c: Int, _ d: Int) -> Int, _ a: Int, _ b: Int) {
let value = mathFunction(a, b)
print(value)
}
// 12
let moveNearerToZero = self.chooseStepFunction(backward: true)
print(moveNearerToZero(100))
func stepForward(_ input: Int) -> Int {
return input + 1
}
func stepBackward(_ input: Int) -> Int {
return input - 1
}
func chooseStepFunction(backward: Bool) -> (Int) -> Int {
return backward ? stepBackward : stepForward
}
// 99
func chooseStepFunction(backward: Bool) -> (Int) -> Int {
func stepForward(input: Int) -> Int { return input + 1 }
func stepBackward(input: Int) -> Int { return input - 1 }
return backward ? stepBackward : stepForward
}