Today, I saw some sample Swift 2.0 (Xcode 7.2) code that can be summarised as:
let colours = ["red", "green", "blue"]
let r1 = colours.contains("The red one.".containsString) // true
let y1 = colours.contains("The yellow one.".containsString) // false
I would have expected a compilation error due to the lack of parenthesis on the containsString()
function. In fact, I'm not even sure how the recursion is working. Are the Strings recursing through each item in the colours
array or vice versa?
Any explanation appreciated.
What you are actually doing is calling the method .contains(predicate: String -> Bool)
(the actual method can throw, but that's not relevant here)
This means that you are asking the array colours
if it contains an element that conforms to that predicate, which is "The red one.".containsString
. So the array is checking its elements one by one and checking it against that predicate. If it finds one, it will return true, otherwise it will return false.
The code above does this:
"The red one.".containsString("red")
"The red one.".containsString("green")
"The red one.".containsString("blue")
"The yellow one.".containsString("red")
"The yellow one.".containsString("green")
"The yellow one.".containsString("blue")
And it checks if it got true
somewhere.
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