Swift計算屬性

來源:互聯網
上載者:User

標籤: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

Swift計算屬性

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.