Swift 中的一些关键字

  • open:可以在任何地方访问、继承和重写

  • public:可以在任何地方被访问,在其他模块不能被继承和重写

  • internal:默认访问级别,在整个模块内都可以被访问

  • fileprivate:可以在同一个文件内被访问、继承和重写

  • private:只能在本类访问和使用,不包括扩展类

  • fallthrough :Swift 中的 switch 语句可以省略 break,满足条件直接跳出循环。fallthrough 则具有贯穿作用,会继续执行后续的 case,直到碰到 break 或 default 才跳出循环。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    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:用于条件判断

    1
    2
    3
    4
    5
    6
    7
    8
    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")
  • inout:将值类型参数以引用方式传递

    1
    2
    3
    4
    5
    6
    var x = 10
    func add(x: inout Int, y: Int) {
    x += y
    }
    add(x: &x, y: 5)
    print(x) // x = 15
  • is & as:is 用于类型判断,as 用于强制转换

    1
    2
    3
    4
    5
    6
    7
    8
    for view : AnyObject in self.view.subviews  
    {
    if view is UIButton
    {
    let btn = view as UIButton;
    println(btn)
    }
    }

    as 使用场合:

  1. 向上转型:

    1
    2
    3
    4
    class Animal {}
    class Cat: Animal {}
    let cat = Cat()
    let animal = cat as Animal
  2. 数值类型转换:

    1
    2
    3
    4
    let num1 = 42 as CGFloat
    let num2 = 42 as Int
    let num3 = 42.5 as Int
    let num4 = (42 / 2) as Double
  3. switch 语句

    1
    2
    3
    4
    5
    6
    7
    switch 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
    9
    func 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 :当需要在方法中修改 structenum 中的成员值时,用 mutating 修饰对应的方法。

您的支持将鼓励我继续创作!
0%