Why is this piece of Swift code compiled? How it works?

Today I saw an example of Swift 2.0 code (Xcode 7.2), which can be summarized 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 was expecting a compilation error due to the lack of parentheses in the function containsString(). Actually, I don’t even know how recursion works. Rows recursive through each element in an array coloursor vice versa?

Any explanation appreciated.

+4
source share
2 answers

What you are actually doing is a method call .contains(predicate: String -> Bool)(the actual method can call, but that doesn't matter here)

, colours, , , "The red one.".containsString. , . , true, false.

:

"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")

, true -.

+6

Swift . Apple :

, ,

containsString() - ( Martin R ). , Swift , .

, , "The red one.".containsString :

String.containsString("The red one.")

(String) -> Bool, , contains :

String.containsString("The red one.")("red")
String.containsString("The red one.")("green")
String.containsString("The red one.")("blue")

, contains:

public func contains(@noescape predicate: (Self.Generator.Element) throws -> Bool) rethrows -> Bool

containsString:

public func containsString(other: String) -> Bool

, predicate String.containsString("The red one.") : a String a Bool. curried.

+5
source

Source: https://habr.com/ru/post/1623755/


All Articles