您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
这篇文章主要介绍“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的类属性作用是什么”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。