エクステンションで、既存の型に新しいサブスクリプトを追加することができます。この例では、Swift の Int 型に整数のサブスクリプトを追加しています。このサブスクリプト [n] は、数値の右から n 番目の数値を返します。

  • 123456789[0] は 9 を返す
  • 123456789[1] は 8 を返す

…など。

extension Int {
    subscript(digitIndex: Int) -> Int {
        var decimalBase = 1
        for _ in 0..<digitIndex {
            decimalBase *= 10
        }
        return (self / decimalBase) % 10
    }
}
746381295[0]
// 5 を返す
746381295[1]
// 9 を返す
746381295[2]
// 2 を返す
746381295[8]
// 7 を返す

リクエストされたインデックスに対する桁が Int 値に無い場合、数値の左がゼロで埋められているかのようにして、サブスクリプトの実装は 0 を返します。

746381295[9]
// 0 を返す、次のようにリクエストされたかのように
0746381295[9]

Portions of this page are translations based on work created and shared by Apple and used according to terms described in the Creative Commons Attribution 4.0 International License.