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

Associated types with protocols

When defining a protocol, there are times when it is useful to define one or more associated types. An associated type gives us a placeholder name that we can use within the protocol in place of a type. The actual type to use for the associated type is not defined until the protocol is adopted. The associated type basically says: We do not know the exact type to use; therefore, when a type adopts this protocol it will define it. As an example, if we were to define a protocol for a queue, we would want the type that adopts the protocol to define the instance types that the queue contains rather than the protocol.

To define an associated type, we use the associatedtype keyword. Let's see how to use associated types within a protocol. In this example, we will illustrate the Queue protocol that will define the requirements needed to implement a queue:

protocol Queue {  
  associatedtype QueueType 
  mutating func addItem(item: QueueType)  
  mutating func getItem() -> QueueType?  
  func count() -> Int 
} 

In this protocol, we define one associated type named QueueType. We then use this associated type twice within the protocol. We use it first as the parameter type for the addItem() method. We then use it again when we define the return type of the getItem() method as an optional type.

Any type that implements the Queue protocol must specify the type to use for the QueueType placeholder, and must also ensure that only items of that type are used where the protocol requires the QueueType placeholder.

Let's look at how to implement Queue in a non-generic class called IntQueue. This class will implement the Queue protocol using the integer type:

struct IntQueue: Queue {  
  var items = [Int]() 
  mutating func addItem(item: Int) {  
    items.append(item) 
  } 
  mutating func getItem() -> Int? {  
    if items.count > 0 { 
      return items.remove(at: 0) 
    } 
    else { 
      return nil 
    } 
  } 
  func count() -> Int {  
    return items.count 
  } 
} 

As we can see in the IntQueue structure, we use the integer type for both the parameter type of the addItem() method and the return type of the getItem() method. In this example, we implemented the Queue protocol in a non-generic way. Generics in Swift allow us to define the type to use at runtime rather than compile time. We will show how to use associated types with generics in Chapter 4, Generics.

Now that we have explored protocols in some detail, let's look at how we can use them in the real world. In the next section, we will see how to use protocols to implement the delegation design pattern.

主站蜘蛛池模板: 昌图县| 宜阳县| 隆德县| 芦山县| 呼伦贝尔市| 思南县| 鸡东县| 尤溪县| 金寨县| 涪陵区| 互助| 蒲江县| 双流县| 德令哈市| 永平县| 徐汇区| 炎陵县| 沂水县| 建水县| 崇仁县| 尼勒克县| 兰州市| 奉贤区| 雷州市| 津南区| 五大连池市| 克拉玛依市| 稷山县| 黎川县| 吉隆县| 汝阳县| 治县。| 黔江区| 五华县| 兴安盟| 永兴县| 上思县| 玛沁县| 柳河县| 民和| 加查县|