Instance Methodswift 6.0.3Swift

indices(where:)

Returns the indices of all the elements that match the given predicate.

iOS
18.0+
macOS
15.0+
tvOS
18.0+
visionOS
2.0+
watchOS
11.0+
func indices(where predicate: (Self.Element) throws -> Bool) rethrows -> RangeSet<Self.Index>

Parameters

predicate

A closure that takes an element as its argument and returns a Boolean value that indicates whether the passed element represents a match.

Returns

A set of the indices of the elements for which predicate returns true.

For example, you can use this method to find all the places that a vowel occurs in a string.

let str = "Fresh cheese in a breeze"
let vowels: Set<Character> = ["a", "e", "i", "o", "u"]
let allTheVowels = str.indices(where: { vowels.contains($0) })
// str[allTheVowels].count == 9