1
3

More than 3 years have passed since last update.

SwiftでArrayの中の全ての要素が、特定の条件を満たすかどうか判定する方法

Posted at

Swift4.2からは allSatisfy メソッドが提供されています

ドキュメント: https://developer.apple.com/documentation/swift/array/2994715-allsatisfy

例:

struct Item {
    var id: String
    var hasStock: Bool
}

let category1 = [
    Item(id: "1", hasStock: true),
    Item(id: "2", hasStock: false),
    Item(id: "3", hasStock: true)
]

let category2 = [
    Item(id: "1", hasStock: false),
    Item(id: "2", hasStock: false),
    Item(id: "3", hasStock: false)
]

print(category1.allSatisfy { $0.hasStock == false }) // -> false
print(category2.allSatisfy { $0.hasStock == false }) // -> true

// 上2つは次の2つと同じ意味だが、allSatisfyメソッドの方がわかりやすい
print(!category1.contains(where: { $0.hasStock == true })) // -> false
print(!category2.contains(where: { $0.hasStock == true })) // -> true
1
3
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
3