zoukankan      html  css  js  c++  java
  • Swift中的willSet与didSet

                    Swift中的willSet与didSet

                        周银辉

    在Swift语言中用了willSet和didSet这两个特性来监视属性的除初始化之外的属性值变化

    无需说太多,看看下面的代码你就能很快明白的

    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
            {
                println("Will set an new value (newValue) to age")
            }
            //我们需要在age属性发生变化后,更新一下nickName这个属性
            didSet
            {
                println("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
    
    println(me.toString())
    
    /*程序输出
    Will set an new value 20 to age
    age filed changed form 0 to 20
    Full Name: Big Zhang San , Age: 20
    */
  • 相关阅读:
    9.8
    9.6
    9.5
    树状数组
    逆序对
    tab标签切换(无炫效果,简单的显示隐藏)
    JQuery 的选择器
    简单的JQuery top返回顶部
    Hello Word!
    java Data 计算自己活了多少天
  • 原文地址:https://www.cnblogs.com/zhouyinhui/p/3804195.html
Copyright © 2011-2022 走看看