Tuesday, July 15, 2014

Working with tuple

Tuples are groups of values combined into a single, compound value. Brand new in Swift, they offer new approach on how to design and code, they particularly play well with functional programming. Very often used as return type of a function. For example, it allows you to return a value combined with an error code. Let's see how to use them with some playground examples:
// Defining a Tuple using parenthesis around the comma-delimited list of values
let httpError404 = (404, "Not found")
let someOtherTuple2:(Double, Bool) = (100, false)

// You can decompose a tuple very easily
var (varStatusCode, varStatusMessage) = httpError404

// Access tuple values with the dot operator followed by their index
httpError404.0
httpError404.1

// Alternatively, you can name the elements of a Tuple
let namedTuple = (statusCode: 404, message: "Not found")
namedTuple.statusCode == namedTuple.0
namedTuple.message == namedTuple.1
I was surprised with Beta3 there are some lacking support for tuple an array/dictionary. In [1] like we define myArray, I'd expect the definition plus instantiation with tuple to work. In [2], not being to append a tuple.
var myArray = [String]()
// [1] Error in playground: invalid use of () to call a value of non-function type
var array1 = [(String, String)]()

var array1: [(String, String)] = []
array1 +=  ("1", "2")
array1

var array2:[(String, String)] = []
var tuple = ("fddfd", "fdfdf")
// [2] Error in playgroungd: Missing argument #2 in call
array2.append(tuple)
array2 += tuple
array2

// Correct in playgroung
var array3:[String] = []
array3.append("ddd")
Another good usage of tuple is with switch statement. You may need to differentiate switch cases depending on 2 criteria. Like in this sample code where the image name dependant on atmospheric measurement plus daylight factor. Tuple can also be used to enumerate through a dictionary
var dict = ["onekey":"onevalue", "twokey":"twovalue"]

for (key, value) in dict {
    dict[key] = "assign-me-sth"
    println("\(key):\(value)")
}
dict


Let's keep an eye on tuple and array.
Try it yourself on Playground format and Happy Swift coding!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.