【技能提升】Swift & struct 比较

前端之家收集整理的这篇文章主要介绍了【技能提升】Swift & struct 比较前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

##struct和class应用场景比较

本质区别 type不同

  1. Struct Value Type是值类型,Class reference type 是引用类型。

使用场景不同

  1. struct SRectangle {
  2. var width = 200
  3. }
  4.  
  5.  
  6. class CRectangle {
  7. var width = 200
  8. }

定义和使用

  1. //struct 使用
  2. var sRect = SRectangle()
  3. // 或者
  4.  
  5. sRect = SRectangle(width:300)
  6.  
  7. sRect.width // 結果就是 300
  1. var cRet = CRectangle()
  2. // class 不能直接用 CRectangle(width:300) 必需要定义一個 constructor
  3. cRect.width // 為 200

赋值给另一个数

  1. //struct
  2. var sRect = SRectangle()
  3. // 或者
  4. var sRect2 = sRect
  5.  
  6. sRect2.width // 目前值是 200,因為 sRect 直接 copy 一份完整記憶體給 sRect2
  7. sRect2.width = 500
  8. sRect.width // sRect.width 值不受 sRect2 影響還是 200
  1. var cRect = CRectangle()
  2. // 或者
  3.  
  4. var cRect2 = cRect
  5.  
  6. cRect2.width // 目前值是 200,因為 sRect 直接 copy 一份完整記憶體給 sRect2
  7. cRect2.width = 500
  8. cRect.width // cRect.width 也改變成了 500

immutable可变性

  1. //struct
  2. let sRect = SRectangle()
  3.  
  4. sRect.width = 500 //编译出错
  1. //class
  2. let cRect = CRectangle()
  3.  
  4. cRect.width = 500 //不会出错

String,Array,Dictionary 都是struct

####mutating function

  1. //struct
  2. // struct 的 function 要去改变 property 的值的時候需要加上 mutating
  3. extension SRectangle {
  4. mutating func changeWidth(width:Int){
  5. self.width = width
  6. }
  7. }
  1. //class
  2. extension CRectangle {
  3. func changeWidth(width:Int){
  4. self.width = width
  5. }
  6. }

####继承inheritance

  1. struct 没有继承,class有继承。

###相同点

Implicit External Parameter Name

  1. //方式1 定义方法
  2.  
  3. func setSize( width:Int,height:Int) {
  4. println("width \(width),height \(height)")
  5. }
  6.  
  7. setSize(50,100)
  1. //方式2
  2. func setSize(width width:Int,height height:Int) {
  3. println("width \(width),height \(height)")
  4. }
  5.  
  6. setSize(width:50,height:100)
  1. //方式3 不常见
  2. func setSize(#width:Int,#height:Int) {
  3. println("width \(width),height:100)

猜你在找的Swift相关文章