LoginSignup
1
2

More than 1 year has passed since last update.

【Swift】特定の条件のみのに適応される配列の extension を記述する方法(where)

Last updated at Posted at 2021-09-26

はじめに

特定の条件のみのに適応される配列の extension を記述したい場合がありました。
調べたところ where を用いるとうまく表現することができたのでそれの紹介になります。

環境:Xcode 12.5.1

やりかた

例: Int の配列のみに適応される extension を書きたい場合

import Foundation

extension Array where Element == Int {
    func doublePrint() {
        self.forEach { print($0 * 2) }
    }
}

let intArray = [1, 2, 3]
intArray.doublePrint()

// 出力
// 2
// 4
// 6

let strArray = ["1", "2", "3"]
strArray.doublePrint() // ← これはコンパイルエラーになる

let strAndIntArray: [Any] = ["1", "2", 3]
strAndIntArray.doublePrint() // ← これもコンパイルエラーになる

ポイント

  • extensionwhere で条件を絞ることができる(Protocolの拡張などでも用いる技)
  • Array の場合 Element で要素の型を得られるので extension Array where Element == "型名" などで絞ることができる
  • where の条件に合わない使い方をするとコンパイルエラーにしてくれる(実行時エラーにはならない)
1
2
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
1
2