筆記5:Properties

在設(shè)計(jì)模型的時(shí)候,經(jīng)常要設(shè)置存值的問(wèn)題,因?yàn)樽詫W(xué)的iOS,心中一直存有疑惑,怎樣的寫法才是正規(guī)專業(yè),怎么樣的寫法是符合swift語(yǔ)言設(shè)計(jì)的?記錄這篇文章的目的也是讓自己好好思考一下這個(gè)問(wèn)題

常見(jiàn)的幾種定義變量的寫法

簡(jiǎn)單的定義一個(gè)變量,并且給予一個(gè)初始值,這樣的代碼量非常小

 var searchRegionID = "2000"

使用get set方法,定義一個(gè)變成,這樣的寫法安全很多

//1
  private var _shouldSearch:Bool = false
    var shouldSearch:Bool{
        get {
            return _shouldSearch
        }
        set{
            _shouldSearch = newValue
        }
    }

//2 只有g(shù)et為只讀屬性,當(dāng)然很安全啦
    private var shouldSear:Bool = false
    var shouldSearch:Bool{
        get {
            return shouldSear
        }
    }
    //2.1 如果只有g(shù)et可以簡(jiǎn)寫
    var shouldSearch:Bool{
            return shouldSear
    }


    func setShouldSearch(newShouldSearch:Bool){
        self.shouldSear = newShouldSearch
    }


我們經(jīng)常還需要定義一些常量(全局變量),我把他們放在一個(gè)constant.swift文件內(nèi),查了一下,apple的文檔中指出

Global variables are variables that are defined outside of any function, method, closure, or type context.Global constants and variables are always computed lazily

一篇Stack overflow回復(fù)中指出, 因?yàn)橹苯佣x全局變量bug很多,用struct封裝一下更安全

struct MyVariables { static var yourVariable = "someString"}

這樣使用它,非常方便

let string = MyVariables.yourVariable
print("Global variable:\(string)")
//Changing value of it
MyVariables.yourVariable = "anotherString"

很多初學(xué)者跟我一樣,iOS用了很久,但在一些Model設(shè)計(jì)時(shí)不知道用Struct還是Class,借這個(gè)節(jié)會(huì)好好了解一下相關(guān)知識(shí),
先上蘋果的文檔

Classes have additional capabilities that structures do not:

1. Inheritance enables one class to inherit the characteristics of another. 
2. Type casting enables you to check and interpret the type of a class instance at runtime. -
3. Deinitializers enable an instance of a class to free up any resources it has assigned.
4. Reference counting allows more than one reference to a class instance.

簡(jiǎn)單的說(shuō)

  1. Class有繼承功能,而Struct沒(méi)有這個(gè)功能
  2. 運(yùn)行時(shí)可以做類型轉(zhuǎn)換
  3. 反初始化時(shí)Class釋放資源
  4. Class通過(guò)引用傳遞,Struct通過(guò)值傳遞

在看別人的文章是,隨手做的幾點(diǎn)摘要

  1. Array和 Dictionary都是 struct
    2.結(jié)構(gòu)體,枚舉以及所有的swift中的基本數(shù)據(jù)類型,包括Array, Dictionary等,全部都是值傳遞的。
  2. 我記得之前用的時(shí)候,NSMutableArray是引用傳遞的。(待驗(yàn)證)
  3. 類方法的聲明和定義需要在關(guān)鍵字func前添加class關(guān)鍵字
  4. willSet和didSet set和get 是不能共存的.
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容