LoginSignup
8

More than 5 years have passed since last update.

Swift で Strideable な独自タイプを実装してみる

Last updated at Posted at 2016-04-13

Swift 3.0 で C言語スタイルの for ループが廃止されるので、その書き換え方法のまとめ
http://qiita.com/codelynx/items/899c26dd2cbdba7d2b00

にも書きましたが、飛び石になる for ループを実装した場合は、Strideable プロトコルを実装してあげるのが良さそうです。そこで、IntDouble とかではなく、独自のタイプの場合どう書けば Strideable を実装できるか試してみる事にしました。

その型の名前は考えたあげく Score にしました。単に、整数 value を持つだけです。 Strideable に適合する為には、distanceTo()advancedBy() を実装するのと、さらに Comparable, Equatable のプロトコルも実装してあげます。

struct Score: Strideable, CustomStringConvertible {

    typealias Stride = Int
    var value: Int

    init(_ value: Int) {
        self.value = value
    }

    func distanceTo(other: Score) -> Int {
        return other.value - value
    }

    func advancedBy(n: Int) -> Score {
        return Score(self.value + n)
    }

    var description: String {
        return String(value)
    }
}

func < (lhs: Score, rhs: Score) -> Bool {
    return lhs.value < rhs.value
}

func == (lhs: Score, rhs: Score) -> Bool {
    return lhs.value == rhs.value
}

では、0 から 100 未満まで 25 づつ stride してみましょう。

for score in Score(0).stride(to: Score(100), by: 25) {
    print(score)  // 0, 25, 50, 75
}

0 から 100 以下まで 25 づつ stride してみましょう。

for score in Score(0).stride(through: Score(100), by: 25) {
    print(score) // 0, 25, 50, 75, 100
}

できました。うまく動くようです。個人的には by の値が Score で指定できないのは、少し引っかかりますが、まぁ良しとします。浮動小数点数を扱いたい場合は… 是非試してみてください。

この記事を書く間に何度も、「Strippable」と打ってスペースキーを押すと「Strippable」に自動変換してくれるのが驚きでした。Appleさん。

では、皆さん Have a happy coding!!

swift --version 
Apple Swift version 2.2 (swiftlang-703.0.18.1 clang-703.0.29)

(参考資料)
https://ez-net.jp/article/24/eO3YibBI/bKdTpaUfz0Ou/
Swift のインデックス型を理解する

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
8