- Swift 4 Protocol-Oriented Programming(Third Edition)
- Jon Hoffman
- 217字
- 2021-07-08 09:42:35
Property requirements
A protocol can require that the conforming types provide certain properties with specified names and types. The protocol does not say whether the property should be a stored or computed property because the implementation details are left up to the conforming types.
When defining a property within a protocol, we must specify whether the property is a read-only or a read-write property by using the get and set keywords. We also need to specify the property's type since we cannot use the type inference in a protocol. Let's look at how we would define properties within a protocol by creating a protocol named FullName, as shown in the next example:
protocol FullName { var firstName: String {get set} var lastName: String {get set} }
In this example, we define two properties named firstName and lastName, which are read-write properties. Any type that conforms to this protocol must implement both of these properties. If we wanted to define the property as read-only, we would define it using only the get keyword, as shown in the following code:
var readOnly: String {get}
It is possible to define static properties by using the static keyword, as shown in the following example:
static var typeProperty: String {get}
Now let's see how we would add method requirements to our protocol.
- 精通Nginx(第2版)
- PHP基礎(chǔ)案例教程
- Mastering QGIS
- RTC程序設(shè)計(jì):實(shí)時(shí)音視頻權(quán)威指南
- Java:Data Science Made Easy
- Linux環(huán)境編程:從應(yīng)用到內(nèi)核
- Unity Shader入門精要
- 深度強(qiáng)化學(xué)習(xí)算法與實(shí)踐:基于PyTorch的實(shí)現(xiàn)
- C語(yǔ)言程序設(shè)計(jì)
- QGIS:Becoming a GIS Power User
- 自學(xué)Python:編程基礎(chǔ)、科學(xué)計(jì)算及數(shù)據(jù)分析(第2版)
- Java Web開(kāi)發(fā)任務(wù)教程
- 軟件測(cè)試實(shí)驗(yàn)實(shí)訓(xùn)指南
- Visual C++實(shí)用教程
- Python High Performance(Second Edition)