Swift Switch语句 就像你看到的,Swift中switch语句有很多优化。 隐式的fall-through行为已经改为了显示的: var (i, j) = (4, -1) // Assign (and create) two variables simultaneously
switch i {
case 1:
j = 1
case 2, 3: // The case for both 2 and 3
j = 2
case 4:
j = 4
fallthrough
case 5:
j++
default:
j = Int.max // The Swift version of INT_MAX
}
就像前面看到的,Switch 语句可以访问枚举的关联值,不过它还可以做更多: var tuple: (Int, Int) // Did I mention that Swift has tuples? :-)
var result: String
tuple = (1,3)
switch tuple {
case (let x, let y) where x > y:
result = "Larger"
case (let x, let y) where x < y:
result = "Smaller"
default:
result = "Same"
}
甚至可以使用String: var s: String = "Cocoa"
switch s {
case "Java": s = "High caffeine"
case "Cocoa": s = "High sugar"
case "Carbon": s = "Lots of bubbles"
default: ()
}
另外,如果你觉得他可以使你的代码更可读,你可以重载~=操作符来改变switch语句的行为。 func ~=(pattern: String, str: String) -> Bool {
return str.hasPrefix(pattern)
}
var s = "Carbon"
switch s {
case "J": s = "High caffeine"
case "C": s = "No caffeine"
default: ()
}
你可以从 Conditional Statements 这篇文章中了解更多关于switch语句的知识。
类与结构体 类似于C++,Swift的类与结构体初看是一样的: 04 | init(_ color: String) { |
07 | func description() -> String { |
08 | return "apple of color \(color)" |
18 | init(_ color: String) { |
21 | func description() -> String { |
22 | return "orange of color \(color)" |
24 | mutating func enripen() { |
主要的不同点在于类是(和块相似的)引用类型,而结构体是(和枚举相似的)数值类型。所以两个变量能够指向同一个(类的)对象,而把一个结构体赋给另外一个变量则必须做一个此结构体的(缓慢的)拷贝。关键词'mutating'告诉调用者enripen()方法不能被常结构体调用。把一个常引用mutating给一个类对象则没有问题。
Swift中大多数内建类型实际上都是结构体。甚至Int型也是。通过点击Cmd你能够看到内建类型的申明,比如Int型的Swift(或者Playground)源码。数组和词典类型也是结构体,但是数组在某些方面表现得像是引用类型:赋值数组并不拷贝每一个元素,实际上你可以更新常数组只要元素的个数保持不变。
在苹果的文档中,你可以读到更多关于Collection Types的内容。
|