Swift 类和结构体(Class And Structure)

2017-11-27  本文已影响0人  zhiyuehl

1.来看看官方说明类和结构体的相同和不同:

Classes and structures in Swift have many things in common. Both can:(相同点)

Classes have additional capabilities that structures do not:(类具有的结构体没有的特点)

注意:
结构在代码中传递时总是被复制,而不使用引用计数。

2.类是引用类型,结构体是值类型

声明一个结构体和类

struct Resolution {
   var width = 0
   var height = 0
}
class VideoMode {
   var resolution = Resolution()
   var interlaced = false
   var frameRate = 0.0
   var name: String?
}
let someResolution = Resolution()
let someResolution2 = Resolution(width: 29, height: 19)
let somVideoMode = VideoMode()
let hd = Resolution(width: 1920, height: 1080)
var cinema = hd

改变cinemawidth,而hdwidth不变,当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"
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"
上一篇 下一篇

猜你喜欢

热点阅读