Swift关键字

153 阅读3分钟

Swift关键字

deinit

  • 析构函数(destructor)
  • 与构造函数相反,当对象结束其声明周期时,系统自动调用
  • OCdealloc函数一样

internal

  • 访问限制
  • internal修饰的属性和方法,只能在模块内部访问。
  • Swift默认修饰符

typealias

  • 定义别名,与OCtypedef类似

staticclass

  • class可以用来声明一个类
  • func之前加上class或者static,都可以用来指定类方法。不同的是class修饰的类方法可以被子类重写,static修饰的静态方法不能被子类重写。
  • class不能修饰存储属性,static可以修饰存储属性,修饰的存储属性被成为静态变量(常量);
  • class修饰的计算属性可以被重写,static修饰的计算属性不能被重写
  • class只能在类中使用,static可以在类、结构体、枚举中使用
  • protocol中一般使用static

mutating

  • 可变的、可修改的
  • 虽然结构体和枚举可以定义自己的方法,但是默认情况下,实例方法中是不可以修改值类型的属性的。为了能够在实例方法中修改属性值,可以再方法定义前添加关键字mutating

lazy

  • lazy修饰的变量,只有在第一次被调用的时候才会去初始化值(即懒加载)。
    class XTTestView: UIView {
        lazy var titleLabel: UILabel = {
            var lab = UILabel()
            lab.frame = CGRect(x: 50, y : 100, width: 200, height: 20)
            lab.textAlignment = .center
            lab.font = UIFont.systemFont(ofSize: 18)
            lab.textColor = UIColor.blue
            return lab
        }()
    }
    

where

  • SQL语句中的where一样,都是附加判断

  • 在集合遍历中,where条件为真时,执行代码块,为假时,不执行

    let array = [0,1,2,3,4,5,6]
    
    array.forEach {
        switch $0 {
        case let x where x > 3 :  // where相当于
            print("后半段")
        default:
            print("默认值")
        }
    }
    
    for value in array where value > 2 {
        print(value)   //输出 3 4 5
    }
    
    for (index, value) in array.enumerated() where index > 2 && value > 3 {
        print("下标 :\(index), 值: \(value)")
    }
    
  • 在补充异常的do/catch里使用,符合条件时,执行函数

    enum SomeError: Error {
        case error1(Int)
        case error2(String)
    }
    
    func methodError() throws {
        throw SomeError.error1(1)
    }
    
    do {
        try methodError()
    } catch SomeError.error1(let param) where param > 2 { // 符合条件时,执行函数
        print(param)
    } catch {
        print("默认异常处理")
    }
    
  • 只给遵守myProtocol协议的UIView添加了拓展

    protocol aProtocol {}
      extension aProtocol where Self: UIView {
      func getString() -> String {
          return "string"
      }
    }
    

fallthrough

  • swiftswitch语句中,break可以不写,满足条件时直接跳出。
  • fallthrough的作用就是,在执行完当前case时,继续执行下面的case(不满足下一个case的条件也会继续执行)
    let index = 15
    switch index {
    case 100:
        print("index is 100")
        fallthrough
    case 10, 15:
        print("index is either  10 or 15")
        fallthrough
    case 5:
        print("index is 5")
    case 6:
        print("index is 6")
    default:
        print("default case")
    }
      //输出结果
    index is either  10 or 15
    index is 5
    

subscript

  • swift中该关键字表示下标,可以让classstruct以及enum使用下标设置或者获取对应属性的值。
    struct Matrix {
        let rows: Int, columns: Int
        var grid: [Double]
        init(rows: Int, columns: Int) {
            self.rows = rows;
            self.columns = columns;
            grid = Array(repeating: 0.0, count: rows * columns)
        }
        func indexIsValid(row : Int, column: Int) -> Bool {
            return row >= 0 && row < rows && column >= 0 && column < columns
        }
    
        ///// subscript
        subscript(row: Int, column: Int) ->Double {
            get {
                assert(indexIsValid(row: row, column: column),"Index out of range")
                return grid[(row * columns) + column ]
            }
            set {
                assert(indexIsValid(row: row, column: column), "index out of range")
                grid[(row * columns) + column] = newValue
            }
        }
    }
    
    var matrix = Matrix(rows: 2, columns: 2)
    matrix[0, 1] = 1.5
    matrix[1, 0] = 3.2
    print("maxtrix == \(matrix)")
    
    //输出结果
    maxtrix == Matrix(rows: 2, columns: 2, grid: [0.0, 1.5, 3.2, 0.0])
    

引用