Reputation: 46533
I am learning Swift3.0 after having a decade of experiences in Objective-C.
While working with tuples, I found it fancy to group many values in one. Once I started comparing it with struct
of Obj-C.
But while passing it to a function or returning from a function the fanciness becomes a pain in ass!
You can not
return
the whole tupleIn both the cases you have to break it into individual datatypes.
Am I getting it right from the above observations?
Upvotes: 1
Views: 971
Reputation: 2372
Here is a solution using typealias
so you don't have to use the tuple repeatedly:
typealias Complex = (Int, Int)
var complex1 = (2, 4)
var complex2 = (3, 5)
func addComplexNumbers(c1:Complex, c2:Complex) -> Complex {
let sum = (c1.0 + c2.0, c1.1 + c2.1)
return sum
}
print("Sum = \(addComplexNumbers(c1:complex1, c2:complex2))")
You can also use named parameters in your tuple, if you intend to retrieve the values separately:
typealias Complex = (x: Int, y: Int)
Upvotes: 3
Reputation: 46533
With the direction provided by Hamish, I got to know binding to a single value called "splatting" is purposefully removed. Looks somewhat in between passing four values instead of just two.
However we can use in this following way:
//This is an example of Complex number.
// 2+4i adding with 3+5i will become 5+9i
var complex1 = (2, 4)
var complex2 = (3, 5)
func addComplexNumbers(c1:(Int, Int), c2:(Int, Int)) -> (Int, Int){
let sum = (c1.0+c2.0, c1.1+c2.1)
return sum
}
print("Sum = \(addComplexNumbers(c1:complex1, c2:complex2))")
Upvotes: 0