Using a method on an array

Here’s an example I saw on apple’s official Swift mannual.

link: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Generics.html#//apple_ref/doc/uid/TP40014097-CH26-ID179

 

 

protocol Container {  

   associatedtype Item: Equatable  

   mutating func append(_ item: Item )  

   var count: Int { get }  

   subscript(i: Int) -> Item { get }  

}  

 

extension Container where Item: Equatable {

   func startsWith(_ item: Item) -> Bool {

      return count >= 1 && self[0] == item

   }

}

 

struct Stack: Container {    

   var items = [Element]()    

   mutating func push(_ item: Element) {    

      items.append(item)    

   }    

   mutating func pop() -> Element {    

      return items.removeLast()    

   }    

   mutating func append(_ item: Element ) {    

      self.push(item)    

   }    

   var count: Int {    

      return items.count    

   }    

   subscript(i: Int) -> Element {    

      return items[i]    

   }    

}

 

 

if [9, 9, 9].startsWith(42) {

   print(“Starts with 42.”)

} else {

   print(“Starts with something else.”)

}

// Prints “Starts with something else.”

 

 

What I couldn’t figure out is the bold part. How could it use the startsWith method on [9, 9, 9]? Cuz only conforming types of the Container protocol have the startsWith(_:) method, and nowhere says that [9, 9, 9] conforms to any protocols, then how could [9, 9, 9] use that method?

Powered by WPeMatico

About

You may also like...

Comments are closed.