Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this Swift code snippet compile? How does it work?

Tags:

xcode

swift

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.

like image 343
Vince O'Sullivan Avatar asked Dec 18 '22 20:12

Vince O'Sullivan


1 Answers

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.

like image 141
vrwim Avatar answered Mar 06 '23 20:03

vrwim