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

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.

主站蜘蛛池模板: 新乐市| 双鸭山市| 昆明市| 兴海县| 潼南县| 封开县| 梅河口市| 桐梓县| 铜陵市| 永城市| 华池县| 平泉县| 邵阳县| 惠州市| 安仁县| 定结县| 额济纳旗| 南岸区| 甘泉县| 桐梓县| 仁布县| 江油市| 家居| 郯城县| 玉龙| 富川| 商都县| 乡城县| 巴马| 民乐县| 潼关县| 渝中区| 电白县| 老河口市| 闸北区| 呼图壁县| 吐鲁番市| 定西市| 黄冈市| 赣榆县| 秦安县|