1.来看看官方说明类和结构体的相同和不同:
Classes and structures in Swift have many things in common. Both can:(相同点)
- Define properties to store values(定义属性来存储值)
- Define methods to provide functionality(定义提供功能的方法)
- Define subscripts to provide access to their values using subscript syntax (定义下标以使用下标语法提供对其值的访问)
- Define initializers to set up their initial state (定义初始化器来设置它们的初始状态)
- Be extended to expand their functionality beyond a default implementation (扩展到超出默认实现的功能)
- Conform to protocols to provide standard functionality of a certain kind (符合协议提供某种标准功能)
Classes have additional capabilities that structures do not:(类具有的结构体没有的特点)
- Inheritance enables one class to inherit the characteristics of another.(继承使一个类能够继承另一个类的特性。)
- Type casting enables you to check and interpret the type of a class instance at runtime.(类型转换使您能够在运行时检查和解释类实例的类型。)
- Deinitializers enable an instance of a class to free up any resources it has assigned.(取消初始化程序使类的一个实例释放它分配的任何资源。)
- Reference counting allows more than one reference to a class instance.(引用计数允许多个对类实例的引用。)
注意:
结构在代码中传递时总是被复制,而不使用引用计数。
2.类是引用类型,结构体是值类型
声明一个结构体和类
struct Resolution {
var width = 0
var height = 0
}
class VideoMode {
var resolution = Resolution()
var interlaced = false
var frameRate = 0.0
var name: String?
}
- 初始化,结构体会自动生成2种初始化方法
let someResolution = Resolution()
let someResolution2 = Resolution(width: 29, height: 19)
let somVideoMode = VideoMode()
- 值类型
所有结构和枚举都是Swift中的值类型。这意味着您创建的任何结构和枚举实例(以及它们作为属性的任何值类型)在您的代码中传递时总是被复制。
如:先生成一个结构体,在赋值另一个
let hd = Resolution(width: 1920, height: 1080)
var cinema = hd
改变cinema
的width
,而hd
的width
不变,当cinema给定当前值时hd,存储在其中的值hd被复制到新cinema实例中。最终结果是两个完全分离的实例,它们恰好包含相同的数值.这情况适合所有的值类型,枚举,字典,数组。。。
cinema.width = 2048
print("cinema is now \(cinema.width) pixels wide")
// Prints "cinema is now 2048 pixels wide"
print("hd is still \(hd.width) pixels wide")
// Prints "hd is still 1920 pixels wide"
- 引用类型
声明一个VideoMode
类
let tenEighty = VideoMode()
tenEighty.resolution = hd
tenEighty.interlaced = true
tenEighty.name = "1080i"
tenEighty.frameRate = 25.0
接下来,tenEighty
被分配一个新的常量,调用alsoTenEighty
,并alsoTenEighty
修改frameRate
:
let alsoTenEighty = tenEighty
alsoTenEighty.frameRate = 30.0
tenEighty的frameRate属性仍为30.0,这既是引用类型
print("The frameRate property of tenEighty is now \(tenEighty.frameRate)")
// Prints "The frameRate property of tenEighty is now 30.0"