Swift get和set方法以及唯讀屬性(計算型屬性,本身不儲存資料,都是通過計算獲得結果)

來源:互聯網
上載者:User

標籤:儲存   死迴圈   person   import   private   return   obj   set   vat   

import UIKit

class Person: NSObject {

    private var _name: String?

    var name: String? {

        get {

            return _name

        }

        set {

            _name = newValue

        }

    }

    //下面的寫法會導致死迴圈

    //    var num: String? {

    //        get {

    //            return self.num

    //        }

    //

    //        set {

    //            self.num = newValue

    //        }

    //    }

    

    //唯讀屬性(又稱為計算型屬性,只重寫get方法)

    var title: String {

        get {

            return "Mr" + (name ?? "")

        }

    }

    //唯讀屬性簡寫

    var title2: String {

        return "Mr XXX"

    }

}

Swift get和set方法以及唯讀屬性(計算型屬性,本身不儲存資料,都是通過計算獲得結果)

相關文章

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.