美文网首页Swift从入门到放弃
Swift 中 几种定义变量的写法

Swift 中 几种定义变量的写法

作者: 婉卿容若 | 来源:发表于2017-03-15 11:37 被阅读1160次

    一直疑惑, 今天在群里遇到,讨论了一下,大致理解

    存储属性 - stored property

    stored property 是所属对象的一部分,占用所属对象的内存
    po 操作是会显示的

    最熟悉的写法
    var nickName = "roni"
        
     var realName:String? // optional
    
    奇怪写法
    var isCounting:Bool = false{
            
            willSet{
                if  newValue
                {
                    countDownTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateTime), userInfo: nil, repeats:true)
                    
                    confirmButton.backgroundColor = UIColor.gray
                }
                else
                {
                    countDownTimer?.invalidate()
                    countDownTimer = nil
                    
                    confirmButton.backgroundColor = UIColor.brown
                }
                
                confirmButton.isEnabled = !newValue
            }
        }
    

    说明:

    1. 事先给 isCounting 赋值为 false
    2. 后面的 block 为 isCounting 属性注册了一个额外的方法, 编译器生成的代码里,在对 isCounting 赋值以后,会调用这个注册的方法
    3. 这里的 willSet 是属性观察器
    延迟存储属性

    主要用于 构造过程,初始值复杂,大量计算等情况

     lazy var test  =  {
            return "boxue"
        }()
    

    下面是错误的写法

     lazy var test  = "text"{
            return "boxue"
        }()
    

    说明:

    1. ** { return "boxue" }() ** 是个方法. 对延迟存储的变量,实现注册一个方法,当调用这个变量时,编译器为这个变量分配内存并调用这个方法返回需要的值给test
    2. 了解使用延迟存储的目的了,就知道上面写法为何错误, 如果事先给 test 赋值 text,那么就直接分配内存了,没有使用懒加载的必要了

    计算属性 - computed property

    computed proporty 不是对象的一部分,不会占用所属对象的内存,
    po 操作是不会显示的, 对 computed property 应该使用 call 命令
    计算属性提供一个getter和一个可选的setter来间接获取、设置其他属性和变量的值
    传说中 Swift 的 set get 方法的写法 --- 我并不怎么用

        var b = ""
        var computed:String {
            set(customValue) {
                b = customValue
              // 如果没有定义customValue,可以直接使用 newValue
              // b = newValue
            }
            get {
                return b
            }
        }
    
     var computed02: String {
            return "boxue"
        }
    

    说明:

    1. computed02 其实是方法, 一个特殊的方法

    相关链接

    Swift-05-存储属性与计算属性

    说明一点: 类型属性 可以是存储属性 或者 计算属性

    相关文章

      网友评论

        本文标题:Swift 中 几种定义变量的写法

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