Swift計算屬性

來源:互聯網
上載者:User
////  main.swift//  Swift計算屬性////  Created by Goddog on 15/7/20.//  Copyright © 2015年 Goddog. All rights reserved.//import Foundationprint("swift的計算屬性類似於Java的setter和getter方法,枚舉、結構體、類都可以定義計算屬性,都有set和get方法哦")/**修飾符 var 計算屬性名稱: 屬性類型{    get    {        //get方法執行體,該方法必須有傳回值    }    set()    {        //set方法執行體,該方法一定不能有傳回值    }}其中修飾符、set可以省略*///枚舉定義了一個計算屬性enum Season{    case Spring, Summer, Fall, Winter    var info: String    {        //定義get方法        get{            print("get方法")            switch(self)            {            case .Spring:                return "春"            default:                return "無"            }        }        //定義set方法        set(newValue){            print("set方法")            print("傳入參數為:\(newValue)")        }    }}var a = Season.Springprint(a.info)      //實際上是調用的getter方法a.info = "秋"      //實際上調用的setter方法//上面的樣本只是簡單賦值,並沒有真正賦值class User{    var first: String = ""    var last: String = ""    //定義計算屬性    var fullName: String    {        //定義計算屬性的first、last兩個屬性決定        get{            return first + "-" + last        }        //定義計算屬性的set方法,改變first、last兩個儲存屬性        set(newValue){            var names = newValue.componentsSeparatedByString("-")            self.first = names[0]            self.last = names[1]        }    }        init(first: String, last: String)    {        self.first = first        self.last = last    }}let s = User(first: "曹", last: "操")print(s.fullName)   //調用get方法s.fullName = "劉-備"print("firstName: \(s.first), lastName: \(s.last)")//MARK: - setter方法簡化/**計算屬性的setter方法提供隱式的形參名,newValue上面可以是set{    var names = newValue.componentsSeparatedByString("-")    self.first = names[0]    self.last = names[1]}*///MARK: - 唯讀計算屬性//只有get部分,沒有set部分的計算屬性稱之為唯讀計算屬性,而且唯讀計算屬性定義部分甚至可以省略get關鍵字和花括弧class Cat{    var first: String = ""    var last: String = ""    //定義唯讀計算屬性,只有get部分(省略了)    var fullName: String    {        return first + "-" + last    }    init(first: String, last: String)    {        self.first = first        self.last = last    }}let name = User(first: "孫", last: "權")print(name.fullName)//唯讀計算屬性不能被賦值,程式只能擷取唯讀計算屬性的值

相關文章

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.