计算性属性:自身值的改变需要计算的,可以使用计算性属性定义
struct Point {
var X: Double = 0.0
var Y: Double = 0.0
}
struct Size {
var width: Double = 0.0
var height: Double = 0.0
}
class Rectangle {
var origin = Point()
var size = Size()
// 计算性属性
var point: Point{
return Point(X: origin.X + size.width * 0.5, Y: origin.Y + size.height * 0.5)
}
// 计算性属性
var point2: Point{
// getter 方法
get {
return Point(X: origin.X + size.width * 0.5, Y: origin.Y + size.height * 0.5)
}
// setter 方法 能够修改属性值, 下面有 2 种写法
/*
set(newOrigin){
origin.X = newOrigin.X - size.width / 2
origin.Y = newOrigin.Y - size.height / 2
}
*/
set{
origin.X = newValue.X - size.width / 2
origin.Y = newValue.Y - size.height / 2
}
}
init(origin: Point, size: Size) {
self.origin = origin
self.size = size
}
}
let newRect = Rectangle(origin: Point(X: 2, Y: 10), size: Size(width: 10, height: 10))
newRect
属性观察器
// 计算性属性
var number: Double = 0 {
/** willSet, didSet 方法不会在初始化(init)的时候调用, 被称为属性观察器 */
willSet{
/** 这里面可以做一些逻辑判断 */
}
didSet{
/** 这里面可以做一些逻辑判断 */
}
---
---
var number = 0 {
willSet {
}
didSet {
}
}
懒加载属性
懒加载属性只能被 `var` 修饰
class Book
{
var name: String
var content: String
// 懒加载 注意,必须使用var 修饰 ()表示调用闭包
lazy var page: Int = {
print("sdfdfs")
var pages = 0
for value in 0...10000 {
pages += value * 10
}
return pages
}()
init?(name: String?, content: String?) {
if name?.count == 0, content?.count == 0 {
return nil
}
self.name = name!
self.content = content!
}
}
if let myBook = Book(name: "XXXXXX", content:"MMMM") {
myBook
myBook.name
myBook.content
myBook.page
}