mutating關鍵字的使用

2021-07-25 01:18:42 字數 914 閱讀 3745

swift中protocol的功能比oc中強大很多,不僅能再class中實現,同時也適用於structenum

使用 mutating 關鍵字修飾方法是為了能在該方法中修改 struct 或是 enum 的變數,在設計介面的時候,也要考慮到使用者程式的擴充套件性。所以要多考慮使用mutating來修飾方法。

首先,先定義乙個protocol

protocol

exampleprotocol

mutating

func

adjust

()}

在上面,定義了乙個exampleprotocol,接下來我們寫乙個class來遵守這個協議

class

******class: exampleprotocol

}// 列印結果

var a = ******class()

a.adjust()

let adescription = a.******description

struct中實現協議exampleprotocol

struct

******struct: exampleprotocol

}

enum中實現協議exampleprotocol

enum

******enum: exampleprotocol

}set

}mutating

func

adjust()

}

swift之mutating關鍵字

原文 在swift中,包含三種型別 type structure,enumeration,class 其中structure和enumeration是值型別 value type class是引用型別 reference type 但是與objective c不同的是,structure和enume...

swift之mutating關鍵字

在swift 中,包含三種型別 type structure,enumeration,class 其中structure和enumeration是值型別 value type class是引用型別 reference type 但是與objective c不同的是,structure和enumera...

swift之mutating關鍵字

在swift 中,包含三種型別 type structure,enumeration,class 其中structure和enumeration是值型別 value type class是引用型別 reference type 但是與objective c不同的是,structure和enumera...