struct比class更“轻量级”(struct更快,class可以承载更多的东西)
就区别来说:
1、struct会自动生成需要的构造方法(constructor),哪个属性没有赋初始值就会生成以哪个属性为参数的构造方法。而class没有,要自己写
// 结构体(值类型)
struct Resolution {
var width = 0
var height = 0
}
let _:Resolution = Resolution(width: 1, height: 3)//结构体类型的成员逐一构造器
// 类(引用类型)
class VideoMode {
var resolution = Resolution()
var name: String?
}
let someVideoMode:VideoMode = VideoMode()
2、struct的属性可以不赋初始值,而class的属性必须赋初始值或者设为可选类型
// 结构体(属性可以不赋初始值)
struct Resolution {
var width:Int
var height:Int
}
let _:Resolution = Resolution(width: 1, height: 3)
// 类(引用类型)
class VideoMode {
// 属性必须赋初始值,或者设为可选类型
var resolution = Resolution(width: 1, height: 2)
var name: String?
}
如果类没有赋初始值或者设为可选类型,那么就会报错cannot be constructed because it has no accessible initializers
3.struct是值类型(Value Type)分配在栈中,是深拷贝。class是引用类型(Reference Type)配在堆中,浅拷贝。
因为struct是值类型放在栈中,那么也就是说struct的释放不归自动引用计数器管
//结构体(值类型),深拷贝
var struct1 = Resolution(width: 1, height: 1)
var struct2 = struct1
struct2.width = 2
print("struct1 = \(struct1)") // 打印结果:struct1 = Resolution(width: 1, height: 1)
//类(引用类型),浅拷贝
var class1 = VideoMode.init()
class1.name = "class1"
var class2 = class1
class2.name = "class2"
print("class1 = \(class1.name)") // 打印结果:class1 = Optional("class2")
4、不可变实例的不同
let class3 = VideoMode.init()
class3.name = "class3" //可以修改
let struct3 = Resolution(width: 2, height: 4)
struct3.height = 4 //报错 Cannot assign to property: 'struct3' is a 'let' constant
5、在实例方法中修改值类型,struct需要在方法前加上mutating
// 结构体(值类型)
struct Resolution {
var width = 0
var height = 0
mutating func changeWidth(width: Int) {
self.width = width
}
}
// 类(引用类型)
class VideoMode {
// class的属性必须赋初始值或者设为可选类型
var resolution = Resolution()
var name: String?
func changeName(name: String) {
self.name = name
}
}