Last active
August 29, 2015 14:10
-
-
Save bjhomer/dc1225ef20a23859438b to your computer and use it in GitHub Desktop.
Swift shorthand argument syntax oddities
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The Swift Programming Language book from Apple states the following: | |
// | |
// Swift automatically provides shorthand argument names to inline closures, | |
// which can be used to refer to the values of the closure’s arguments by the | |
// names $0, $1, $2, and so on. | |
// In Xcode 6.1 and 6.2b1, it appears that this is only true IF the last argument | |
// is referenced using shorthand syntax somewhere in the closure body. See below | |
// for details. | |
func test(block: (Int)->Void) { | |
block(1) | |
} | |
test { println($0) } // prints "1" | |
println("\n") | |
func test2(block: (Int, Int)->Void) { | |
block(1, 2) | |
} | |
test2 { println($0) } // prints "(1, 2)" ???? $0 is the whole tuple??? | |
test2 { println($1) } // prints "2" | |
test2 { println($0); $1} // prints "1" ???? ... but only if other arguments are unused? | |
println("\n") | |
func test3(block: (Int, Int, Int)->Void) { | |
block(1, 2, 3) | |
} | |
test3 { println($0) } // prints "(1, 2, 3)" ???? okay, at least we're being consistent | |
test3 { println($2) } // prints "3" | |
test3 { println($1) } // !!! Does not compile !!! | |
// error: tuple types '(Int, Int, Int)' and '(($T2, ($T2, $T3) -> ($T2, $T3) -> $T1) -> ($T2, ($T2, $T3) -> $T1) -> $T1, (($T2, $T3) -> ($T2, $T3) -> $T1, $T3) -> (($T2, $T3) -> $T1, $T3) -> $T1)' have a different number of elements (3 vs. 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment