LoginSignup
0
0

More than 5 years have passed since last update.

[Swifty]モデルもプロトコルへ

Posted at

モデルの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]
    }
}

ソースコード
GitHubからどうぞ。

https://github.com/murakami/workbook/tree/master/ios/Hand - GitHub

関連情報
文化を調和させる

【Cocoa練習帳】
http://www.bitz.co.jp/weblog/

http://ameblo.jp/bitz/(ミラー・サイト)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0