1.存储属性与计算属性
存储属性类似于结构变量,存储在实例的内存中,结构体和类都能定义存储属性。在创建实例的时候,必须为所有的存储属性设置一个初始值。
计算属性本质就是方法,它不占用实例的内存,枚举,结构体和类都能定义计算属性。定义计算属性,只能用var。
例子:
struct Square {
//存储属性
var width: Int
//计算属性
var area: Int {
set {
width = newValue / 2
}
get {
width * 2
}
}
}
var square = Square(width: 10)
square.area = 30
print("width:\(square.width) area:\(square.area)")2.延迟存储属性
使用lazy可以定义一个延迟存储属性,在第一次用到属性的时候才会进行初始化。
一般用var修饰。
例子:
class Test {
lazy var imageView: UIImageView = {
let image = UIImageView()
return image
}()
}
3.属性观察器
willSet会传递新值,默认叫newValue,didSet会传递旧值,默认叫oldValue,在初始化时,设置属性不会触发观察器,在属性定义时设置初始值也不会触发。
例子:
struct Cricle {
var radius: Double {
willSet {
print("willSet:",newValue)
}
didSet {
print("didset:",oldValue,radius)
}
}
init() {
self.radius = 1.0
print("Cricle init")
}
}
var c = Cricle()
c.radius = 1.54.inout的本质总结
- 如果实参有物理内存地址,且没有设置属性观察器,直接将实参的内存地址传入函数。
- 如果实参是计算属性或设置了属性观察器,则先复制实参的值,作为局部变量传递地址给函数,函数内部修改局部变量的值,返回时再将局部变量的值覆盖实参的值。
- 总结起来本质就是引用传递(地址传递)
例子:
func test( t: inout Int){
t = 20
}
var k = 50
test(t: &k)
5.类型属性
类型属性只能通过类型返回。
存储类型属性在整个程序运行过程中,就只有1份内存。如单例。
我们可以通过static来定义类型属性,如果是类也可以用class来修饰属性,而且需要设置初始值,它实际上默认就是lazy,会在第一次使用才初始化。
例子:
struct StaticType {
static var width: Int = 0
init() {
StaticType.width += 1
}
}
let s1 = StaticType()
let s2 = StaticType()
let s3 = StaticType()
print(StaticType.width)6.单例模式
例子:
class Manager {
//简单的单例写法
public static let share = Manager()
private init(){}
}
class Manager2 {
public static let share = {
//设置单例需要多逻辑操作
//....
return Manager2()
}()
private init(){}
}上一篇文章:swift从入门到精通07-闭包