iOS/iPhone/iPad/watchOS/tvOS/MacOSX/Android プログラミング, Objective-C, Cocoa, Swiftなど
モデルのHandをDataTypeプロトコル適用ということにして、項目名をCardから汎用的なItemに変更する。
protocol DataType {
var numberOfItems: Int {get}
func addNewItem(at index: Int) -> Self
func deleteItem(at index: Int) -> Self
func moveItem(fromIndex: Int, toIndex: Int) -> Self
}
struct Hand: DataType {
private var deck = Deck()
private var cards = [Card]()
public init() {
}
public init(deck: Deck, cards: [Card]) {
self.deck = deck
self.cards = cards
}
public var numberOfItems: Int {
return cards.count
}
public func addNewItem(at index: Int) -> Hand {
return insertCard(card: deck.nextCard(), at: index)
}
private func insertCard(card: Card, at index: Int) -> Hand {
var mutableCards = cards
mutableCards.insert(card, at: index)
return Hand(deck: deck, cards: mutableCards)
}
public func deleteItem(at index: Int) -> Hand {
var mutableCards = cards
mutableCards.remove(at: index)
return Hand(deck: deck, cards: mutableCards)
}
public func moveItem(fromIndex: Int, toIndex: Int) -> Hand {
return deleteItem(at: fromIndex).insertCard(card: cards[fromIndex], at: toIndex)
}
subscript(index: Int) -> Card {
return cards[index]
}
}