Swift · Searching and Counting

Searching and Counting

6.0.0-rc.1 · 91a27bdd

Substring search returns the Index? of the first or last match, or nil when the needle is absent.

let haystack = "Hello, world! Hello, Swift!"
let first = haystack.findFirst(substring: "Hello")   // Index of position 0
let last = haystack.findLast(substring: "Hello")     // Index of the second "Hello"
assert(first == haystack.startIndex)
assert(haystack.findFirst(substring: "Rust") == nil)

Byte-set search locates the first or last byte that belongs to, or is excluded from, a set of characters. The character set is itself any string-like value, treated as a bag of bytes.

let text = "  trim me  "
let firstNonSpace = text.findFirst(characterNotFrom: " ")  // first non-blank byte
let lastNonSpace = text.findLast(characterNotFrom: " ")    // last non-blank byte
let firstVowel = text.findFirst(characterFrom: "aeiou")    // first vowel
let lastVowel = text.findLast(characterFrom: "aeiou")      // last vowel

All six finders are generic over the needle type, so you can search a String for a String.UTF8View needle and vice versa.