Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using String's enumerateLines function in Swift

Tags:

swift

The enumerateLines function of Swift's String type is declared like this:

enumerateLines(body: (line: String, inout stop: Bool) -> ())

As I understand it, this declaration means: "enumerateLines is a function taking a closure, body, which is handed two variables, line and stop, and returns void."

According to the Swift Programming Language book, I believe I should thus be able to call enumerateLines in a nice terse fashion with a trailing closure, like this:

var someString = "Hello"

someString.enumerateLines()
{
    // Do something with the line here
}

..but that results in a compiler error:

Tuple types '(line: String, inout stop: Bool)' and '()' have a different number of elements (2 vs. 0)

So then I try explicitly putting in the arguments, and doing away with the trailing closure:

addressString.enumerateLines((line: String, stop: Bool)
{
    // Do something with the line here
})

...but that results in the error:

'(() -> () -> $T2) -> $T3' is not identical to '(line: String.Type, stop: Bool.Type)'

In short, no syntax that I've tried has resulted in anything that will successfully compile.

Could anybody point out the error in my understanding and provide a syntax that will work please? I'm using Xcode 6 Beta 4.

like image 971
davidf2281 Avatar asked Aug 02 '14 14:08

davidf2281


1 Answers

The closure expression syntax has the general form

{ (parameters) -> return type in
    statements
}

In this case:

addressString.enumerateLines ({
    (line: String, inout stop: Bool) -> () in
    println(line)
})

Or, using the trailing closure syntax:

addressString.enumerateLines {
    (line: String, inout stop: Bool) in
    println(line)
}

Due to automatic type inference, this can be shortened to

addressString.enumerateLines {
    line, stop in
    println(line)
}

Update for Swift 3:

addressString.enumerateLines { (line, stop) in
    print(line)

    // Optionally:
    if someCondition { stop = true }
}

Or, if you don't need the "stop" parameter:

addressString.enumerateLines { (line, _) in
    print(line)
}
like image 133
Martin R Avatar answered Sep 30 '22 18:09

Martin R