1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Swift】Array の contains の挙動の整理

Last updated at Posted at 2021-08-23

はじめに

よく Array の contains の挙動について忘れるので、まとめてみました。

基本的な挙動

// (基本形の挙動)クロージャーの返りがひとつでもtrueが含まれればtrueを返却する
print([0,1].contains { _ in true }) // ture
print([2,3].contains { _ in false }) // false

// (備考)空配列の場合はクロージャーを1周も通過しないため必ずfalseを返す(はず)
print([].contains { _ in true }) // false
print([].contains { _ in false }) // false

以下、 0を含むか? のいろいろな書き方 (全部同じ意味のはず)

// (1) 一番長いタイプ
print([0,1].contains(where: { num in num == 0 })) // true
print([2,3].contains(where: { num in num == 0 })) // false

// (2) 引数を省略
print([0,1].contains(where: { $0 == 0 })) // true
print([2,3].contains(where: { $0 == 0 })) // false

// (3) whereを省略
print([0,1].contains { num in num == 0 }) // true
print([2,3].contains { num in num == 0 }) // false

// (4) whereを省略かつ引数を省略 ← 迷ったらこれにしてます
print([0,1].contains { $0 == 0 }) // true
print([2,3].contains { $0 == 0 }) // false

// (5) クロージャーを省略
print([0,1].contains(0)) // true
print([2,3].contains(0)) // false

さいごに

contains は結構便利!!

1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?