swift基础之类属性

原创
2021/04/14 21:08
阅读数 19

延迟存储属性 lazy

//延迟存储属性 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

//属性观察者 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.
展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部