【swift-总结】属性
2015-07-07 14:23
260 查看
属性分为存储属性和计算属性
存储属性
没有setter和getter方法/** * 存储属性 */ struct MyRange { var firstValue: Int let length: Int } var range = MyRange(firstValue: 0, length: 3) range.firstValue = 3; ///结构体常量不能改变里面的存储属性 let constMyRange = MyRange(firstValue: 5, length: 6)
懒加载属性
//在属性前面添加一个lazylazy vay count: Int
计算属性
计算属性拥有set和Get方法/** * 计算属性 */ 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 { let centerX = origin.x + size.width / 2 let centerY = origin.y + size.height / 2 return Point(x: centerX, y: centerY) } set(newValue) { origin.x = newValue.x - size.width / 2 origin.y = newValue.y - size.height / 2 } } } var square = Rect(origin: Point(x: 0.0, y: 0.0), size: Size(width: 10.0, height: 10.0)) let squareCenter = square.center square.center = Point(x: 15.0, y: 15.0)
属性监测器
willSet和didSet方法class StepCount { var total:Int = 0 { willSet { print("willSet run") } didSet { print("didSet run") } } } var stepCounter = StepCount() ///开始会执行willSet方法,赋值完以后会执行didSet方法 stepCounter.total = 200
类型属性
类型属性是用类型名直接访问的/** * 类型属性 */ struct myStruct { static var myString = "hello" static var intProperty: Int { return 5 } } enum myEnum { static var myString = "hello" static var intProperty: Int { return 5 } } class myClass { //类中不支持存储属性位类属性 // class var myString = "hello" class var intProperty: Int { return 5 } }
相关文章推荐
- Swift 的nil
- Swift 2.0语法更新(三)
- swift 的宏定义
- Apple Swift编程语言入门教程
- Swift Error fatal error: unexpectedly found nil while unwrapping an Optional value
- iOS8发展~Swift(三)UI详细解释
- swift之桥接模式
- Swift 看值类型和引用类型
- Swift教程-集合
- swift中闭包 OC中Block 解决循环引用
- Swift教程-新操作符
- Swift教程-基本类型
- IOS学习之旅-Swift-函数
- IOS学习之旅-Swift-常量、变量、字符串
- Swift 如何将数字型字符串转换成String类型 (toInt()方法) 及返回值未解包的原因
- swift 断言(assert)
- Swift高级语法学习总结(转)
- Swift基础语法学习总结(转)
- swift 之 URL编码
- Swift学习笔记系列——(3)集合类型