struct Circle {
var radius:Double. // 存储属性
var diameter: Double {. // 计算属性
set {
radius = newValue/2
}
get {
radius*2
}
}
}

struct Point {
var x:Int
var y:Int {
get {
return 10
}
}
}
上述代码中,y只设置了get方法,其实相当于只读属性,就行写操作的时候,是会报错的


示例
enum Season:Int {
case spring = 1,summer,autmn,winter
var rawValue: Int {
get {
switch self {
case .spring:
return 1
case .summer:
return 2
case .autmn:
return 3
case .winter:
return 4
}
}
}
}
在枚举中,有rawValue,在正常的使用中
var season = Season.summer
print(season.rawValue)
可以看出是正常调用的,但是我们可以对枚举的这个rawValue进行重写,其实更像一种计算属性,在上图上图中可以看出,我们定义了一个get方法,正常调用season.rawValue也是没问题的
枚举rawValue原理

延迟存储属性


属性观察器
willSet,didSet只用在存储属性上,willSet,didSet与set,get方法是不能共存的,也没必要共存
struct Circle {
var radius:Double {
willSet {
print("willset",newValue)
}
didSet {
print("didset",oldValue,radius)
}
}
var diameter: Double {
set {
radius = newValue/2
}
get {
radius*2
}
}
}


属性观察器、计算属性的功能,同样可以应用在全局变量、局部变量上

inout的本质总结

类属性
struc Shape {
var width:int = 0
static var height:Int = 0
}
Shape.height = 10 // 类属性,加入static描述的话,可以通过类来访问

单例模式
public class FileManger {
public static let shared = FileManger()
private init() { }
}// 第一种写法
public class FileManger {
public static let shared = {
return FileManger()
}()
private init() { }
} // 第二种写法
网友评论