##struct和class应用场景比较
本质区别 type不同
- Struct Value Type是值类型,Class reference type 是引用类型。
使用场景不同
- struct SRectangle {
- var width = 200
- }
- class CRectangle {
- var width = 200
- }
定义和使用
- //struct 使用
- var sRect = SRectangle()
- // 或者
- sRect = SRectangle(width:300)
- sRect.width // 結果就是 300
- var cRet = CRectangle()
- // class 不能直接用 CRectangle(width:300) 必需要定义一個 constructor
- cRect.width // 為 200
赋值给另一个数
- //struct
- var sRect = SRectangle()
- // 或者
- var sRect2 = sRect
- sRect2.width // 目前值是 200,因為 sRect 直接 copy 一份完整記憶體給 sRect2
- sRect2.width = 500
- sRect.width // sRect.width 值不受 sRect2 影響還是 200
- var cRect = CRectangle()
- // 或者
- var cRect2 = cRect
- cRect2.width // 目前值是 200,因為 sRect 直接 copy 一份完整記憶體給 sRect2
- cRect2.width = 500
- cRect.width // cRect.width 也改變成了 500
immutable可变性
- //struct
- let sRect = SRectangle()
- sRect.width = 500 //编译出错
- //class
- let cRect = CRectangle()
- cRect.width = 500 //不会出错
String,Array,Dictionary 都是struct
####mutating function
- //struct
- // struct 的 function 要去改变 property 的值的時候需要加上 mutating
- extension SRectangle {
- mutating func changeWidth(width:Int){
- self.width = width
- }
- }
- //class
- extension CRectangle {
- func changeWidth(width:Int){
- self.width = width
- }
- }
####继承inheritance
- struct 没有继承,class有继承。
###相同点
Implicit External Parameter Name
- //方式1 定义方法
- func setSize( width:Int,height:Int) {
- println("width \(width),height \(height)")
- }
- setSize(50,100)
- //方式2
- func setSize(width width:Int,height height:Int) {
- println("width \(width),height \(height)")
- }
- setSize(width:50,height:100)
- //方式3 不常见
- func setSize(#width:Int,#height:Int) {
- println("width \(width),height:100)