加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift中的willSet与didSet

发布时间:2020-12-14 02:39:48 所属栏目:百科 来源:网络整理
导读:import Foundationclass People : NSObject{ //普通属性 var firstName:String = "" var lastName:String = "" var nickName:String = "" //计算属性 var fullName:String { get { return nickName + " " + firstName + " " + lastName } } //带属性监视器的
import Foundation


class People : NSObject
{
    //普通属性
    var firstName:String = ""
    var lastName:String  = ""
    var nickName:String  = ""
    
    //计算属性
    var fullName:String
        {
        get
        {
            return nickName + " " + firstName + " " + lastName
        }
    }
    
    //带属性监视器的普通属性
    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) "
    }
    
}

var me = People()
me.firstName = "Zhang"
me.lastName  = "San"
me.age = 20

print(me.toString())
<p class="p1"><span class="s1"><strong>Will set an new value 20 to age</strong></span></p><p class="p1"><span class="s1"><strong>age filed changed form 0 to 20</strong></span></p><p class="p1"><span class="s1"><strong>Full Name: Big Zhang San,Age: 20</strong></span></p>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读