在Swift中,包含三种类型(type): structure,enumeration,class
其中structure和enumeration是值类型(value type),class是引用类型(reference type)
Swift中protocol的功能比OC中强大很多,不仅能再class中实现,同时也适用于struct、enum。但是struct、enum都是值类型,每个值都是有默认的,所以在实例方法中不能改变,因此就要用mutating关键字,这个关键字可以让在此方法中值的改变,会返回到原始结构里边
protocol Vehicle {
var numberOfWheels: Int {get}
var color: UIColor {get set}
mutating func changeColor()
}
struct MyCar: Vehicle {
let numberOfWheels = 4
var color = UIColor.blue
mutating func changeColor() {
color = .red
}
}
这段代码中不加mutating关键字,编译器就会报错
网友评论