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

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.

主站蜘蛛池模板: 永昌县| 梅河口市| 金塔县| 桃源县| 曲靖市| 灌阳县| 苏州市| 冀州市| 昭觉县| 广宁县| 武汉市| 滨海县| 丘北县| 遂平县| 武清区| 玉门市| 山东省| 视频| 盐源县| 巴林左旗| 北流市| 孝义市| 长泰县| 桂东县| 香港| 巴彦县| 富民县| 丹棱县| 永年县| 海兴县| 普宁市| 普定县| 青河县| 宽甸| 武陟县| 隆昌县| 垫江县| 武汉市| 建始县| 含山县| 昌邑市|