这篇文章主要介绍“swift的类属性作用是什么”,在日常操作中,相信很多人在swift的类属性作用是什么问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”swift的类属性作用是什么”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
网站建设哪家好,找创新互联!专注于网页设计、网站建设、微信开发、小程序定制开发、集团企业网站建设等服务项目。为回馈新老客户创新互联还提供了商洛免费建站欢迎大家使用!
//延迟存储属性 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 */
//计算属性 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 { //在值被存储之前调用 willSet(newTotalSteps) { print("About to set totalSteps to \(newTotalSteps)") } //在新值在存储之后调用 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 */
//类型属性 class SomeClass { static var storedTypeProperty = "Some Value." static var computedTypeProperty: Int { return 27 } } print(SomeClass.storedTypeProperty) //Some Value.
到此,关于“swift的类属性作用是什么”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注创新互联网站,小编会继续努力为大家带来更多实用的文章!