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")
}
This can be done succinctly with:
if prefixes.contains(where: number.hasPrefix) {
print("found")
}
So, how does this work?
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).
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:)
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With