官术网_书友最值得收藏!

Method requirements

A protocol can require that the conforming types provide specific methods. These methods are defined within the protocol exactly as we define them within a class or structure, but without the curly brackets and method body. We can define that these methods are instance or type methods using the static keyword. Adding default values to the method's parameters is not allowed when defining the method within a protocol.

Let's add a method named getFullName() to the FullName protocol:

protocol FullName { 
  var firstName: String {get set}  
  var lastName: String {get set} 
 
  func getFullName() -> String 
} 

The fullName protocol now requires one method named getFullName() and two read-write properties named firstName and lastName.

For value types, such as the structure, if we intend for a method to modify the instances that it belongs to, we must prefix the method definition with the mutating keyword. This keyword indicates that the method is allowed to modify the instance it belongs to. The following example shows how to use the mutating keyword with a method definition:

mutating func changeName() 

If we mark a method requirement as mutating, we do not need to write the mutating keyword for that method when we adopt the protocol with a reference (class) type. The mutating keyword is only used with value (structures or enumerations) types.

主站蜘蛛池模板: 高台县| 定兴县| 汤原县| 宣武区| 绥阳县| 吉林省| 钟山县| 桃园市| 张家港市| 洪雅县| 正宁县| 梨树县| 永兴县| 商洛市| 海宁市| 浠水县| 卓尼县| 阳泉市| 宁海县| 盖州市| 嫩江县| 广平县| 综艺| 游戏| 武功县| 蒲江县| 龙泉市| 安新县| 且末县| 邵阳县| 拜城县| 通山县| 高安市| 常州市| 华阴市| 安阳县| 房产| 常宁市| 衢州市| 蓝田县| 罗源县|