Reputation: 515
I'm trying to evaluate if an entered string partially matches any item in an array. When I use the following method in playgrounds it seems to work properly. However, when I use the exact same method in Xcode 9.0 beta 6 (9M214v) it doesn't return the correct answer.
func isValid(_ item: String) -> Bool {
let whitelist = ["https://apple.com","https://facebook.com","https://stackoverflow.com"]
return whitelist.contains(where: {$0 <= item ? true : false })
}
There's also anomalies like when I passed in "https://twitter.com" it'll return true. Am I nuts? And while I'm here, anyone have a different approach to solve this problem?
Upvotes: 1
Views: 7252
Reputation: 31645
theres also anomalies like when I passed in "https://twitter.com" it'll return true.
Whether the version of Swift is 3 or 4, based on your code snippet you should get the same true
result! Why?
because the logic of contains(where:)
of doing the comparison is related to the logic of the equality of the given elements, i,e you cannot use contains
with array of non-equatable elements. To make it more clear:
"https://apple.com" <= "https://twitter.com"
"https://facebook.com" <= "https://twitter.com"
"https://stackoverflow.com" <= "https://twitter.com"
the result would be true
for all statements ('t' character is greater than 'a', 'f' and 's').
Thus:
"https://zwebsite" <= "https://twitter.com"
would returns false
('t' is less than 'z').
However, to get the expected result, you could implement your function like this:
func isValid(_ item: String) -> Bool {
let whitelist = ["https://apple.com","https://facebook.com","https://stackoverflow.com"]
return whitelist.contains { $0 == item }
}
Or for even a shorter contains
:
return whitelist.contains(item)
Which leads to let
isValid("https://twitter.com")
to returns false
.
Upvotes: 3
Reputation: 38833
Just return the following, which will return true
or false
:
return whitelist.contains(item)
Upvotes: 0