LoginSignup
1
2

More than 5 years have passed since last update.

配列のある範囲にあるマッチした要素の数を調べる Swift

Last updated at Posted at 2017-08-15

配列のある範囲にあるマッチした要素の数を調べる swift

Swiftの配列はrange(for文で範囲指定するアレ)を使ってスライス(ある範囲の配列を取り出す)ことができる.
そしてfilterでマッチする要素を取り出して
countで数える.
以下のコードでは配列arrの中の1番から6番までのindexの中の要素が3である個数を調べる

let arr = [1,2,3,2,5,3,4,5,5,3,2,3]

let t = arr[1...6].filter({$0 == 3}).count
print(t)

output

2

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