Chapter Tuple
Chapter Tuple
import Foundation
class ChapterTuple {
func callPrintFunctions(){
tupleComparison()
}
func tupleComparison(){
func useOfTupleMeans(){
// Tuples group multiple values into a single compound value. The values
within a tuple can be of any type and do not have to be of the same type as each
other.
let tuple = ("one", 2, "three")
print("first value of tuple = \(tuple.0)")
print("second value of tuple = \(tuple.1)")
print("third value of tuple = \(tuple.2)")
// They can also be named when being used as a variable and even have the
ability to have optional values inside:
var numbers: (optionalFirst: Int?, middle: String, last: Int)
numbers = (nil, "dos", 3)
print("number tuple = \(numbers)")
}
func useOfGetFromTuple(){
let myTuple = (name : "Naminder kaur", age : 40)
let (first, second) = myTuple
print("first = \(first)")
print("second = \(second)")
// Specific properties can be ignored by using underscore (_):
let longTuple = ("abc", 123, "xyz")
let (_,_,third) = longTuple
print("third = \(third)")
}
func useOfTupleAsReturnFunc(){
let myTuple = self.tupleReturner()
print("First Value = \(myTuple.0)")
print("Second Value = \(myTuple.1)")
}
func tupleReturner()->(Int, String){
return (100, "Hundred")
}
func useOfTupleForSwaping(){
// Tuples are useful to swap values between 2 (or more) variables without
using temporary variables.
var a = "Naminder"
var b = "Samyra"
(b,a) = (a,b)
print("a = \(a)")
print("b = \(b)")
}
func useOfTupleForSwitch(){
let switchTuple = (First: true, Second: false)
switch switchTuple {
case (true, true):
print("true, true")
case (true, false):
print("true, false")
case (false, true):
print("false, true")
case (false, false):
print("false, false")
}
}
}