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

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.

主站蜘蛛池模板: 四平市| 隆安县| 清涧县| 略阳县| 林州市| 海盐县| 永泰县| 陇西县| 玉溪市| 都昌县| 沁水县| 年辖:市辖区| 闽清县| 盈江县| 隆安县| 邻水| 河东区| 翼城县| 恩平市| 汉沽区| 高唐县| 大港区| 吕梁市| 邢台市| 吉首市| 镇巴县| 邻水| 新密市| 汝阳县| 新丰县| 连江县| 敖汉旗| 博罗县| 庆安县| 鲜城| 龙川县| 宜春市| 库尔勒市| 安阳县| 固阳县| 武川县|