美文网首页
swift中set和get 的书写规范

swift中set和get 的书写规范

作者: 东方诗空 | 来源:发表于2022-03-10 14:43 被阅读0次

swift中set和get 的书写规范

    var c:Int {
        get{
            // 这里 不论是 c 还是 self.c 都会造成 crash  原因是方法的死循环
            // 而且 不能像 OC 中 写上 _c
            return 1
        }
        
        set{
            // 我们测试 写上 self.c = newValue 和 不写 都会造成 crash
            // 而且 不能像 OC 中 写上 _c
            a = newValue
            print("Recived new value", newValue, " and stored into 'A' ")
        }
    }
    
    // 使用了 外部的一个变量来重写了这个 方法
    var _tittle:String?
    var tittle: String?{
        set{
            _tittle=newValue
        }
        get{
            return _tittle
        }
    }
    
    // 如果只重写 get 方法,默认为 readOnly
    var age:Int?{
        return 20
    }
    
    // swift 中有储值属性和计算属性,一般 我们只是给计算属性添加 get set 方法
    //  在set、get方法中有相应的计算
    var num:Int = 0
    var ddd:Int {
        get{
            return num+11
        }
        set{
            num = num + newValue
        }
    }
    
    // 存储属性: 就是存储一个变量 或 常量  懒加载也属于存储型属性 类似于OC中的方法
    let aaa = "aaa"
    lazy var ccc:[TestModel] = {
        let testModel = TestModel()
        var arr = [TestModel]()
        for _ in 0...99{
            arr.append(testModel)
        }
        //
        return arr
    }()
    
    // swift 中使用了willset 和 didSet 这连个特性 来见识属性的除初始化之外的 属性值变化
    // 和 OC 比较,我们可以在didSet 里面执行一些改变UI的操作
    var newAge:String?{
        
        willSet{
            //
            print("===========")
        }
        
        didSet{
            print("did set " + newAge!)
        }
    }
    

相关文章

网友评论

      本文标题:swift中set和get 的书写规范

      本文链接:https://www.haomeiwen.com/subject/caifdrtx.html