Swift中 Class和Struct的區別

來源:互聯網
上載者:User

標籤:實值型別   span   自動產生   記憶體   final   存在   需要   進階   操作符   

類(Class)和結構體(Struct)區別

1.  記憶體管理方式不一樣, 類參考型別, 分配在堆上。 結構體實值型別,分配在棧上。 

2. 類, 有析構。 結構體不能有析構, playground中測試直接卡死。

3. 結構體建構函式, 會自動產生帶參數的構造器。類不會對有初始化賦值的屬性, 產生帶參數的構造器。

2. 類有繼承特性,結構體沒有繼承特性,自然也不存在對成員屬性和成員方法, 類屬性和類方法的重載。

正因為結構體沒有繼承, 所以操作符函數, 需要static修飾, 而不能用class修飾;

struct : static func +(left:A,right:A) -> A {...}
class: static func +(left:A,right:A) -> A {...} 或者
final class func +(left:A,right:A) -> A {...}

相同點1, 其他進階特性都差不多,結構體和類都有的特性:

操作符函數, 範型, 協議採納, 觀察器

Swift中 Class和Struct的區別

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.