Sunday 9 September 2018

Tuples

Why Tuples ?
Swift 4 has introduced tuples to help us to return multiple values from a function instead of only one value.
Tuples is multiple values grouped into a single compound value. The values can be of any type, it need not necessarily to be of same type.
Tuples type is comma-seperated list types, enclosed in parentheses.
Tuples are created by grouping any amount of values.

Please check below examples for different uses of tuples :
---------------------------------------------------------------------------------
Displaying tuple value using variable name

1) Same Data type

let multipleValue : (value1 : String,value2 : String) = ("iOS","Android")

print(multipleValue.value1)
print(multipleValue.value2)

Output
iOS
Android
---------------------------------------------------------------------------------
Different Data type

1) Displaying tuple value using index (without variable name)

let multipleValue = ("iOS""Android"5)

print(multipleValue.0
print(multipleValue.1)
print(multipleValue.2)

Output :
iOS
Android
5

2) Displaying tuple value using variable names

let multipleValue = (name: "iOS",name1: "Android",value1: 5)

print(multipleValue.name)
print(multipleValue.name1)
print(multipleValue.value1)

Output :
iOS
Android
5
---------------------------------------------------------------------------------
Displaying tuples as optionals

var multipleValue : (name: String,name1: String?,value1: Int)
multipleValue = ("iOS",nil,5)

print(multipleValue.name)
print(multipleValue.name1)
print(multipleValue.value1)

Output
iOS
nil
5

---------------------------------------------------------------------------------
Tuples usage in function return type

1) Displaying tuple value using index (without variable name)

func test() -> (String,Int) {
    return ("iOS",11)
}

print(test().0)
print(test().1)

Output
iOS
11

2) Displaying tuple value with variable name


func test() -> (name : String,version : Int) {
    return ("iOS",11)
}
print(test().name)
print(test().version)

Output
iOS
11
---------------------------------------------------------------------------------

For more info, click on below link :-

https://www.youtube.com/watch?v=MwOv844k9-4&t=222s




Thank you.


No comments:

Post a Comment