Swift计算属性


一、计算属性的概念

        

        计算属性本身不存储数据,而是从其它存储属性中计算得到数据,与存储属性不同,类、结构体、和枚举都可以定义计算属性


        计算属性提供了一个getter来获取值,以及一个可选的setter来间接设置其它属性或变量的值,计算属性的语法如下:


        面向对象类型 类型名{

                存储属性...

                var 计算属性名:属性数据类型{

                    get {

                        return 计算后属性值

}

                set 新属性值{

                    

}


}

        示例:

class Employee {
            var no:Int = 0
            var firstName:String = ""
            var lastName:String = ""
            var job:String?
            var salary:Double = 0
            lazy var dept:Department = Department()
            var fullname:String{
                get{
                return firstName+"."+"lastName"
}
                set(newFullName)系统默认给的变量名为newvalue{
                    var name = newFullName.componentsSeperatedByString(".")
                    firstName = name[0]
                    lastName = name[1]
}
}
}


二、只读计算属性

            计算属性可以只有getter访问器,没有setter访问器,这就是只读计算属性


            示例:


class Employee {
            var no:Int = 0
            var firstName:String = ""
            var lastName:String = ""
            var job:String?
            var salary:Double = 0
            lazy var dept:Department = Department()
            var fullname:String{
                get{
                return firstName+"."+"lastName"
}
               
}
}



三、结构体和枚举中的计算属性


        示例


    struct Department {

            let no:Int = 0

            var name : String = "sales"

            

            var fullName:String {

                return "swift" + name + ".D"

}

}


        var dept = Department()

        println(dept.fullName)


         enum WeekDays:String {

                case Monday = "Mon"

                case Tuesday = "Tue"

                case Wednesday = "Wed"

                case Thursday = "Thu"

                case Friday = "Fri"

                var message:String {

                    return "Today is"+self.rawValue

}

}

var day = WeekDays.Monday

println(day.message)


本文出自 “平凡之路” 博客,请务必保留此出处http://linjohn.blog.51cto.com/1026193/1621924

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。