1
1

【Swift】配列の全ての要素が条件に一致しているかをチェックする

Last updated at Posted at 2023-11-18

はじめに

配列の全ての要素が条件に一致しているかをチェックする機能があることを知ったので記事にしておきます。

実装

let array = ["acerola", "almond", "apple", "avocado"]

// 配列の全ての要素にaが含まれているかを判定
array.allSatisfy { $0.contains("a") } // true

// 配列の全ての要素にbが含まれているかを判定
array.allSatisfy { $0.contains("b") } // false

// 配列の全ての要素にcが含まれているかを判定
array.allSatisfy { $0.contains("c") } // false

空の配列に対しては常にtrueが返されるので注意が必要です。

let array = [String]()
array.allSatisfy { $0.contains("a") } // true

おわり

これ結構便利ですね
allSatisfyがない場合、filterreduceを使って同じ事ができそうですが、冗長になりそうですね

公式ドキュメント

1
1
2

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
1