Sunday 4 June 2017

Tuples In Swift Programming

A tuple in Swift is a construct that groups multiple values together into a single compound value. Tuples can be useful when more than one value type can provide more useful information about the outcome of a behavior or action than simply returning a single value. They are meant to be temporary and are not suited for more complex data structures that will probably persist beyond a temporary scope

var person = ("Sachin", "Ramesh")

Named elements:
You can name the elements from a tuple and use those names to refer to them. An element name is an identifier followed by a colon(:).

var person = (firstName: "Sachin", lastName: "Ramesh")

var firstName = person.firstName // Sacin
var lastName = person.lastName // Ramesh

Accessing a Tuple:

let (firstName, lastName) = person
print(firstName) => "Sachin"
print(lastName) => "Ramesh"

let (onlyFirstName, _) = person
print(onlyFirstName)=> "Sachin"

Indexing a Tuple:
let firstName = person.0
let lastName = person.1
print(firstName) => "Sachin"
print(lastName) => "Ramesh"

Accessing it's Named Values:
let person = (firstName: "Sachin", lastName: "Ramesh")
print(person.firstName) => "Sachin"
print(person.lastName) => "Ramesh"

Functions and Tuples:
Tuples can also be useful as a return type for a function to return multiple values as part of a single compound value. Continuing with our code example, let's build out the function that's responsible for returning this tuple.

// Function Definition
func getFullName() -> (firstName: String, lastName: String) {
  let person = (firstName: "Sachin", lastName: "Ramesh")     //Assume getting from HTTP.get(url)
  return (person.firstName, person.lastName)
}

// Calling the Function
let person = getFullName()
print(person.firstName) => "Sachin"
print(person.lastName) => "Ramesh"

No comments: