Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift String hasPrefix Using an Array of Strings

Tags:

swift

I want to avoid the if statement in the sample code below, and instead make a single call to hasPrefix on my number string and pass in the prefixes array. Is there a way to do this in Swift?

let prefixes: [String] = ["212", "213", "214"]
let number: String = "213-555-1212"

if number.hasPrefix("212") || number.hasPrefix("213") {
    print("found")
}
like image 462
Adam Avatar asked Nov 15 '18 21:11

Adam


1 Answers

This can be done succinctly with:

if prefixes.contains(where: number.hasPrefix) {
    print("found")
}

So, how does this work?

  1. contains(where:) takes a closure that gets called for each element of the prefixes array to decide if the element matches the desired condition. Since prefixes is an array of String, that closure has the signature (String) -> Bool, meaning it takes a String and returns a Bool. contains(where:) will continue to call the given closure for each element in the prefixes array until it gets a true returned, or until it runs out of items in the prefixes array, at which time the answer is false (prefixes doesn't contain an item that matches the condition).

  2. In this case, we are passing the function number.hasPrefix as the closure. Normally you'd use number.hasPrefix by calling it with an argument like this: number.hasPrefix("212"). Without the argument, number.hasPrefix refers to the function hasPrefix called on number and that function has the signature we're looking for: (String) -> Bool. So it can be used as the closure for contains(where:).

  3. So, prefixes.contains(where: number.hasPrefix) takes each prefix from the array and checks if number.hasPrefix(prefix) returns true. If it finds one, it stops searching and returns true. If all of them return false, then prefixes.contains(where:) returns false.

like image 137
vacawama Avatar answered Nov 15 '22 12:11

vacawama