In Swift, how is tuple related to function argument?
In the following two examples the function returns the same type even though one takes a tuple while the other takes two arguments. From the caller standpoint (without peeking at the code), there is no difference whether the function takes a tuple or regular arguments.
Is function argument related to tuple in some ways?
e.g.
func testFunctionUsingTuple()->(Int, String)->Void {
func t(x:(Int, String)) {
print("\(x.0) \(x.1)")
}
return t
}
func testFuncUsingArgs()->(Int, String)->Void {
func t(x:Int, y:String) {
print("\(x) \(y)")
}
return t
}
do {
var t = testFunctionUsingTuple()
t(1, "test")
}
do {
var t = testFuncUsingArgs()
t(1, "test")
}
There is also inconsistencies in behavior when declaring tuple in function argument in a regular function (rather than a returned function):
func funcUsingTuple(x:(Int, String)) {
print("\(x.0) \(x.1)")
}
func funcUsingArgs(x:Int, _ y:String) {
print("\(x) \(y)")
}
// No longer works, need to call funcUsingTuple((1, "test")) instead
funcUsingTuple(1, "test")
funcUsingArgs(1, "test3")
UPDATED:
Chris Lattner's clarification on tuple:
"x.0” where x is a scalar value produces that scalar value, due to odd behavior involving excessive implicit conversions between scalars and tuples. This is a bug to be fixed.
In "let x = (y)”, x and y have the same type, because (x) is the syntax for a parenthesis (i.e., grouping) operator, not a tuple formation operator. There is no such thing as a single-element unlabeled tuple value.
In "(foo: 42)” - which is most commonly seen in argument lists - you’re producing a single element tuple with a label for the element. The compiler is currently trying hard to eliminate them and demote them to scalars, but does so inconsistently (which is also a bug). That said, single-element labeled tuples are a thing.
func funcUsingTuple(x:(Int, String))you have to explicitly pass a tuple:funcUsingTuple((1, "test"))