美文网首页
计算型属性用法

计算型属性用法

作者: 玉米地里种玉米 | 来源:发表于2019-03-15 15:25 被阅读0次
    class People {
        
        //普通属性
        var firstName:String = ""
        var lastName:String  = ""
        var nickName:String  = ""
        
        /// 计算属性
        var fullName: String {
            get{
                return "1" + "2" + "3"
            }
        }
        /// //带属性监视器的普通属性
        
        var age:Int = 0 {
            //我们需要在age属性变化前做点什么
            willSet {
                print("Will set an new value \(newValue) to age")
            }
            // //我们需要在age属性发生变化后,更新一下nickName这个属性
            didSet {
                 print("age filed changed form \(oldValue) to \(age)")
                if age<10
                {
                    nickName = "Little"
                }else
                {
                    nickName = "Big"
                }
            }
        }
        func toString() -> String {
            return "Full Name: \(fullName) " + ", Age: \(age) "
        }
    }
    
    let me = People()
    me.firstName = "Li"
    me.lastName  = "Lei"
    me.age = 30
    
    print(me.toString())
    

    相关文章

      网友评论

          本文标题:计算型属性用法

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