swift:談談swift幾種常見屬性的區別

來源:互聯網
上載者:User

標籤:blog   mon   str   person   總結   更新   全域   16px   tag   

一、前奏

Swift作為一門新語言,經過幾年的發展,逐漸趨於完善,目前已經更新到3.0版本,它彙集許多其他語言的特點,例如JS、Paython等,完全區別於OC。個人感覺它沒有完全的OOP和OOD的性質。

  二、談談幾種屬性的區別儲存屬性

定義:實實在在儲存常量和變數的

計算屬性

定義:依賴於儲存屬性,通過計算得出來,它提供getter訪問值,提供setter方法間接給其他屬性或者變數設定值

類屬性

定義:其本質其實就是一個全域屬性,在類裡限定了其範圍,用關鍵字static修飾

懶載入屬性

定義:該屬性在使用的時候初始化一次,用關鍵字lazy修飾,必須進行初始化,非執行個體屬性懶載入時在大括弧{}後面要加上()

全域屬性

定義:類外面的屬性,範圍全域。類似於OC的static修飾的屬性

class ViewController: UIViewController {    override func viewDidLoad() {        super.viewDidLoad()        //執行個體屬性        let p = Person()      
//儲存屬性 print(p.age)
//懶載入屬性 print(p.name)
//類屬性 print(Person.height)
//計算屬性 print(p.getAge)
//全域屬性 print(commonProperty) }}//全域屬性var commonProperty = {()->String in print("Common Property1") return "Common Property" }()class Person{ //類屬性 static var height = {()->Int in print("Static Properties") return 170 }() //儲存屬性 var age = {()->Int in print("Store properties") return 26 }() //計算屬性 var getAge:Int{ get{ print("Computed Properties") return age } } //懶載入屬性 lazy var name = {()->String in print("Lazy Properties") return "Lazy liyang" }() //構造方法 init(){ print("init") }}

 

三、總結:基於類,類的構造

  • 儲存屬性,最先被初始化
  • 構造方法,僅次於儲存屬性調用,可以在這裡對儲存屬性進行賦值
  • 懶載入屬性、類屬性、全域屬性都是在第一次使用的時候初始化一次,以後調用都不在初始化
  • warning:當懶載入屬性是基於一個儲存屬性計算的時候,切勿使用懶載入屬性,採用計算屬性

 

swift:談談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.