這篇文章主要介紹“swift的類(lèi)屬性作用是什么”,在日常操作中,相信很多人在swift的類(lèi)屬性作用是什么問(wèn)題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”swift的類(lèi)屬性作用是什么”的疑惑有所幫助!接下來(lái),請(qǐng)跟著小編一起來(lái)學(xué)習(xí)吧!
網(wǎng)站建設(shè)哪家好,找創(chuàng)新互聯(lián)!專(zhuān)注于網(wǎng)頁(yè)設(shè)計(jì)、網(wǎng)站建設(shè)、微信開(kāi)發(fā)、小程序定制開(kāi)發(fā)、集團(tuán)企業(yè)網(wǎng)站建設(shè)等服務(wù)項(xiàng)目。為回饋新老客戶(hù)創(chuàng)新互聯(lián)還提供了商洛免費(fèi)建站歡迎大家使用!
//延遲存儲(chǔ)屬性 lazy class DataImporter { var fileName = "data.txt" init() { print("DataImporter inits") } } class DataManager { lazy var importer = DataImporter() var data = [String]() } let manager = DataManager() manager.data.append("Some data") manager.data.append("Some more data") print("manager.data.append finish") //manager.data.append finish print(manager.importer.fileName) /* DataImporter inits data.txt */
//計(jì)算屬性 struct Point { var x = 0.0, y = 0.0 } struct Size { var width = 0.0, height = 0.0 } struct Rect { var origin = Point() var size = Size() var center: Point { get { Point(x: origin.x + (size.width / 2), y: origin.y + (size.height / 2)) } set { origin.x = newValue.x - (size.width / 2) origin.y = newValue.y - (size.height / 2) } } } let rect = Rect(origin: Point(x: 2, y: 2), size: Size(width: 4, height: 4)) print(rect.center) //Point(x: 4.0, y: 4.0)
//屬性觀察者 willSet & didSet class StepCounter { var totalSteps: Int = 0 { //在值被存儲(chǔ)之前調(diào)用 willSet(newTotalSteps) { print("About to set totalSteps to \(newTotalSteps)") } //在新值在存儲(chǔ)之后調(diào)用 didSet { if totalSteps > oldValue { print("Added \(totalSteps - oldValue) step") } } } } let stepCounter = StepCounter() stepCounter.totalSteps = 200 stepCounter.totalSteps = 360 stepCounter.totalSteps = 456 /* About to set totalSteps to 200 Added 200 step About to set totalSteps to 360 Added 160 step About to set totalSteps to 456 Added 96 step */
//類(lèi)型屬性 class SomeClass { static var storedTypeProperty = "Some Value." static var computedTypeProperty: Int { return 27 } } print(SomeClass.storedTypeProperty) //Some Value.
到此,關(guān)于“swift的類(lèi)屬性作用是什么”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)?lái)更多實(shí)用的文章!