extension of typealias❓

typealias 可以有 extension 嗎?可以遵循 protocol 嗎?

public let cards = [
  ("🂡", 11), ("🂢", 2), ("🂣", 3), ("🂤", 4), ("🂥", 5), ("🂦", 6), ("🂧", 7), ("🂨", 8), ("🂩", 9), ("🂪", 10), ("🂫", 10), ("🂭", 10), ("🂮", 10),
  ("🂱", 11), ("🂲", 2), ("🂳", 3), ("🂴", 4), ("🂵", 5), ("🂶", 6), ("🂷", 7), ("🂸", 8), ("🂹", 9), ("🂺", 10), ("🂻", 10), ("🂽", 10), ("🂾", 10),
  ("🃁", 11), ("🃂", 2), ("🃃", 3), ("🃄", 4), ("🃅", 5), ("🃆", 6), ("🃇", 7), ("🃈", 8), ("🃉", 9), ("🃊", 10), ("🃋", 10), ("🃍", 10), ("🃎", 10),
  ("🃑", 11), ("🃒", 2), ("🃓", 3), ("🃔", 4), ("🃕", 5), ("🃖", 6), ("🃗", 7), ("🃘", 8), ("🃙", 9), ("🃚", 10), ("🃛", 10), ("🃝", 10), ("🃞", 10)
]

public typealias Card = (String, Int)
public typealias Hand = [Card]

// ⭐️ typealias 竟然可以有 extension ‼️
//    這相當於對 Array<Element> where Element == Card 做 conditional conformance
public extension Hand {
  var cardString: String { return map { $0.0 }.joined()     }
  var points    : Int    { return map { $0.1 }.reduce(0, +) }
}

// Q: typealias 可以 conform to protocols 嗎❓
// A: 答案是不行。

/* 
compiler warning
----------------
conformance of 'Array<Element>' to protocol 'CustomStringConvertible' 
conflicts with that stated in the type's module 'Swift' and will be ignored; 
there cannot be more than one conformance, even with different conditional bounds.
*/
extension Hand: CustomStringConvertible {
    public var description     : String { return self.string }
}

Array<Element>Swift 模組中,原本就已經遵循 CustomStringConvertible。上面 compiler warning 告訴我們:不能另外再宣告遵循 CustomStringConvertible,就算用 conditional conformance 也不行❗

Last updated