【技能提升】Swift & struct 比较
发布时间:2020-12-14 06:16:14 所属栏目:百科 来源:网络整理
导读:##struct和class应用场景比较 本质区别 type不同 Struct Value Type是值类型,Class reference type 是引用类型。 使用场景不同 struct SRectangle { var width = 200}class CRectangle { var width = 200} 定义和使用 //struct 使用var sRect = SRectangle(
##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 //不会出错
####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) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |