您可以定义一个继承自的CardCollection 协议
RangeReplaceableCollectionType,
和一个带有默认实现的协议扩展来转发所有
底层collective数组的访问方法:
struct Card {
// Simplified for demonstration purposes:
let rank : Int
let suit : Int
}
protocol CardCollection : RangeReplaceableCollectionType {
var collective : [Card] { get set }
}
extension CardCollection {
var startIndex : Int { return collective.startIndex }
var endIndex : Int { return collective.endIndex }
subscript(position : Int) -> Card {
get {
return collective[position]
}
set(newElement) {
collective[position] = newElement
}
}
mutating func replaceRange<C : CollectionType where C.Generator.Element == Card>(subRange: Range<Int>, with newElements: C) {
collective.replaceRange(subRange, with: newElements)
}
}
然后
struct Deck: CardCollection {
var collective = [Card]()
}
struct Hand: CardCollection {
var collective = [Card]()
}
都符合RangeReplaceableCollectionType,可以处理
像一个数组:
var deck = Deck()
deck.append(Card(rank: 1, suit: 1))
deck[0] = Card(rank: 2, suit: 3)
for card in deck {
print(card)
}
var hand = Hand()
hand.append(deck.first!)
如果Deck/Hand 是类而不是结构,那么它们
需要final 或有required init() 方法,
比较
Why use required Initializers in Swift classes?.
稍微通用一点,你可以定义一个ElementCollection
协议(独立于Card 类型)
它的行为就像一个数组(通过符合
RangeReplaceableCollectionType) 并将访问权限转发到
底层elements 数组:
protocol ElementCollection : RangeReplaceableCollectionType {
typealias Element
var elements : [Element] { get set }
}
extension ElementCollection {
var startIndex : Int { return elements.startIndex }
var endIndex : Int { return elements.endIndex }
subscript(position : Int) -> Element {
get {
return elements[position]
}
set(newElement) {
elements[position] = newElement
}
}
mutating func replaceRange<C : CollectionType where C.Generator.Element == Element>(subRange: Range<Int>, with newElements: C) {
elements.replaceRange(subRange, with: newElements)
}
}
然后用作
struct Card {
// Simplified for demonstration purposes:
let rank : Int
let suit : Int
}
struct Deck: ElementCollection {
var elements = [Card]()
}
struct Hand: ElementCollection {
var elements = [Card]()
}