【技能提升】Swift & struct 比较

##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)

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...