-
open
:可以在任何地方访问、继承和重写 -
public
:可以在任何地方被访问,在其他模块不能被继承和重写 -
internal
:默认访问级别,在整个模块内都可以被访问 -
fileprivate
:可以在同一个文件内被访问、继承和重写 -
private
:只能在本类访问和使用,不包括扩展类 -
fallthrough
:Swift 中的 switch 语句可以省略 break,满足条件直接跳出循环。fallthrough 则具有贯穿作用,会继续执行后续的 case,直到碰到 break 或 default 才跳出循环。
switch 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
:用于条件判断
let 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")
-
is & as
:is 用于类型判断,as 用于强制转换
for view : AnyObject in self.view.subviews
{
if view is UIButton
{
let btn = view as UIButton;
println(btn)
}
}
as
使用场合:
- 向上转型:
class Animal {}
class Cat: Animal {}
let cat = Cat()
let animal = cat as Animal
- 数值类型转换:
let num1 = 42 as CGFloat
let num2 = 42 as Int
let num3 = 42.5 as Int
let num4 = (42 / 2) as Double
- switch 语句
switch animal {
case let cat as Cat:
print("如果是Cat类型对象,则做相应处理")
case let dog as Dog:
print("如果是Dog类型对象,则做相应处理")
default: break
}
as!
用于强制转换,转换失败会导致程序崩溃,而 as?
转换失败时会返回一个 nil 对象。
-
guard
:与 if 相反,当不满足条件时执行后面的语句。
func test(input: Int?) {
guard let _ = input else {
print("Input cannot be nil")
return
}
}
test(input: nil)
// print "Input cannot be nil"
-
static
:和class
关键词一样,都用来生成类方法,不同的是,class
修饰的方法可以被重写,而static
不行。 -
mutating
:当需要在方法中修改struct
、enum
中的成员值时,用mutating
修饰对应的方法。
网友评论