open
:可以在任何地方访问、继承和重写public
:可以在任何地方被访问,在其他模块不能被继承和重写internal
:默认访问级别,在整个模块内都可以被访问fileprivate
:可以在同一个文件内被访问、继承和重写private
:只能在本类访问和使用,不包括扩展类fallthrough
:Swift 中的 switch 语句可以省略 break,满足条件直接跳出循环。fallthrough 则具有贯穿作用,会继续执行后续的 case,直到碰到 break 或 default 才跳出循环。1
2
3
4
5
6
7
8
9switch integerToDescribe {
case 1, 3, 5, 7, 11, 13, 17, 19:
description += " a prime number, and also";
fallthrough // 执行到此并不跳出循环,而是继续执行case5
case 5:
description += " an integer" // 执行到这一步,跳出循环
default :
description += " finished"
}
where
:用于条件判断1
2
3
4
5
6
7
8let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y:
println("(\\(x), \\(y)) is on the line x == y")
case let (x, y) where x == -y:
println("(\\(x), \\(y)) is on the line x == -y")
case let (x, y):
println("(\\(x), \\(y)) is just some arbitrary point")inout
:将值类型参数以引用方式传递1
2
3
4
5
6var x = 10
func add(x: inout Int, y: Int) {
x += y
}
add(x: &x, y: 5)
print(x) // x = 15is & as
:is 用于类型判断,as 用于强制转换1
2
3
4
5
6
7
8for view : AnyObject in self.view.subviews
{
if view is UIButton
{
let btn = view as UIButton;
println(btn)
}
}as
使用场合:
向上转型:
1
2
3
4class Animal {}
class Cat: Animal {}
let cat = Cat()
let animal = cat as Animal数值类型转换:
1
2
3
4let num1 = 42 as CGFloat
let num2 = 42 as Int
let num3 = 42.5 as Int
let num4 = (42 / 2) as Doubleswitch 语句
1
2
3
4
5
6
7switch animal {
case let cat as Cat:
print("如果是Cat类型对象,则做相应处理")
case let dog as Dog:
print("如果是Dog类型对象,则做相应处理")
default: break
}
as!
用于强制转换,转换失败会导致程序崩溃,而 as?
转换失败时会返回一个 nil 对象。
guard
:与 if 相反,当不满足条件时执行后面的语句。1
2
3
4
5
6
7
8
9func test(input: Int?) {
guard let _ = input else {
print("Input cannot be nil")
return
}
}
test(input: nil)
// print "Input cannot be nil"defer
:该关键字包裹的一段代码会延迟执行,当前作用域结束的时候会被调用。当同一个作用域指定多个defer
代码块,在当前作用域结束时,先定义的后执行,后定义的先执行。static
:和class
关键词一样,都用来生成类方法,不同的是,class
修饰的方法可以被重写,而static
不行。mutating
:当需要在方法中修改struct
、enum
中的成员值时,用mutating
修饰对应的方法。