- Swift 4 Protocol-Oriented Programming(Third Edition)
- Jon Hoffman
- 220字
- 2021-07-08 09:42:35
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.
- Learning RxJava
- 體驗設計原理:行為、情感和細節
- Wireshark Network Security
- 小程序,巧運營:微信小程序運營招式大全
- Scala謎題
- OpenShift在企業中的實踐:PaaS DevOps微服務(第2版)
- Linux Device Drivers Development
- .NET 3.5編程
- Corona SDK Mobile Game Development:Beginner's Guide(Second Edition)
- Python圖形化編程(微課版)
- IBM Cognos Business Intelligence 10.1 Dashboarding cookbook
- OpenStack Networking Essentials
- Arduino可穿戴設備開發
- 從Excel到Python數據分析:Pandas、xlwings、openpyxl、Matplotlib的交互與應用
- SignalR:Real-time Application Development(Second Edition)