Created
April 21, 2015 16:42
-
-
Save erica/e7d45e13611a14dd79d6 to your computer and use it in GitHub Desktop.
More than anyone really wants to know about tuples and closures/functions
This file contains 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
import UIKit | |
typealias Tupletype = (a:Int, b:String, c:Double) | |
let params1 = (1, "Params1", 2.4) // anonymous tuple | |
let params2 : Tupletype = (1, "Params2", 2.4) // named parameter tuple | |
// Standard tuple: var myclosure: (Int, String, Double) -> () | |
var myclosure = {(a:Int, b:String, c:Double)->() in println("\(a) \(b) \(c)")} | |
myclosure(params1) // works | |
// myclosure(params2) // does not work | |
// Using tuple type: var myclosure2: Tupletype -> () | |
var myclosure2:Tupletype->() = {println("\($0.a) \($0.b) \($0.c)")} | |
myclosure2(params1) // works | |
myclosure2(params2) // works | |
// Extra argument in call, expects a tuple argument | |
// myclosure2(5, "Anonymous Params", 9.8) // does not work | |
// myclosure2(a:5, b:"Bye", c:9.8) // does not work | |
// But when passed a proper tuple it works | |
myclosure2((a:5, b:"ParamTuple", c:9.8)) // works | |
myclosure2((5, "AnonymousTuple", 9.8)) // works | |
// Mismatched argument list, does not work | |
// myclosure2((x:5, y:"Anonymous tuple", z:9.8)) // does not work | |
// And now onto functions | |
// Standard function, expects 3 arguments | |
func myfunction(a: Int, b:String, c:Double){println("\(a) \(b) \(c)")} | |
myfunction(5, "Whatever", 9.8) // works because this is the standard way to call it | |
// myfunction(a:5, b:"Bye", c:9.8) // does not work because extraneous argument labels | |
myfunction(params1) // works when passed a non-labeled tuple | |
// myfunction(params2) // does not work when passed a parameterized tuple, even though the parameters match | |
// Function with tuple argument | |
func myfunction2(tuple:Tupletype){println("\(tuple.a) \(tuple.b) \(tuple.c)")} | |
myfunction2((5, "AnonymousTuple", 9.8)) // works as expected | |
myfunction2((a:5, b:"ParamTuple", c:9.8)) // and works with matching tuple names | |
myfunction2(params1) // works with anonymous tuple | |
myfunction2(params2) // works with typed labeled tuple | |
// myfunction2((x:5, y:"MismatchTuple", z:9.8)) // does not work because mismatched param labels |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment