LoginSignup
2

More than 5 years have passed since last update.

[Swifty]Self要件

Posted at

本件、プロジェクトの構成の違いから、最後はグダグダになってしまったので、一通り巡ったということで、その中で気になったことを調べてみることにする。

プロトコルでSelfを返すように変更したが、何となく意味は分かるのだが、何なんだろう。The Swift Programming Languageを読み返してみたが、それらしい記述がない。検索したところ、おそらく、WWDCの発表からだろうか。Self要件と説明しているサイトを見つけた。

protocol DataType {
    var numberOfItems: Int {get}
    func addNewItemAtIndex(index: Int) -> Self
    func deleteItemAtIndex(index: Int) -> Self
    func moveItem(fromIndex: Int, toIndex: Int) -> Self
}

このプロトコルを適用したクラスの型として扱われるということのようだ。

ただ、これはプロトコルでのみ許されているようで、適用したクラスでは、そのクラスで宣言しないとエラーとなった。

struct Hand: DataType {
    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)
    }
}

Self要件によって、プロトコルは、総称型のように、適用した型を抽象的に記述できるということのようだ。

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

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

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

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

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

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
2