What are the typical use cases for Tuples in Swift or OOP in general?

I started a new iOS project about 4 months ago in Swift to learn the language. While I was developing it, I almost never used tuples in the entire program. This is because I'm really used to Java and Objective-C which don't have tuples.

I've heard a thing or two about tuples and Apple seems to be very worried about adding them to Swift, but I find it hard to find a really useful case for them.

I understand and use them for one thing so far: quick-class replacer. Instead of creating a new class with the sole purpose of keeping multiple properties together, use a tuple instead. But even then, I only used one tuple, because many times these properties affect each other, so those methods that change these properties are better contained in a class with these properties. So is this really an advantage?

But what are some other really useful design patterns used in OOP (or Swift) that people who are new to tuples should know about?

Thank!

+3


source to share


2 answers


A few examples from the standard library might help.

A common need is to return not only one value from a function, but two different values ​​as well. So, for example, the protocol _IntegerArithmeticType

contains:

static func addWithOverflow(lhs: Self, _ rhs: Self) -> (Self, overflow: Bool)

      

That is, it returns a new value plus a boolean indicator of whether an overflow has occurred:

let i: UInt8 = 0xFF
let (j, overflow) = UInt8.addWithOverflow(i, 1)
if overflow { println("Oh noes!") }

      

Without a tuple, you will have to resort to inout

for one of the results or return a different structure.

A collection Dictionary

contains two types for its element, key and value. They are often grouped together, so they Dictionary

define a type Element

as a tuple of two:

struct Dictionary<Key : Hashable, Value> : CollectionType, DictionaryLiteralConvertible {
    typealias Element = (Key, Value)
}

      



Then, when you iterate over the dictionary, each element you get is that pair, and the built-in destructuring of tuples allows you to conveniently split them in two:

// either treat them as a pair:
for element in myDictionary { }

// or destructure them:
for (k, v) in myDictionary { }

      

Now, in theory, both of these examples could be done by defining new structures. So, for example, with the overflow case:

struct ResultWithOverflow<T: _IntegerArithmeticType> {
    let value: T
    let overflow: Bool
}

static func addWithOverflow(lhs: Self, _ rhs: Self) -> ResultWithOverflow<Self>

      

It is important to understand, however, that tuples are not used here simply because pain is to define this additional structure (although this is true). There is more of it because this extra structure is a mess - it interferes with reading the function. If you want to know what you did addWithOverflow

, you need to see what happened ResultWithOverflow

. Instead, with a tuple, it's pretty clear that what is returned in the function definition is what is returned.

Likewise, if there were a structure DictionaryElement

that was what the dictionary contained as its element, it would also be an added complication that could help understand how dictionaries work.

This is a trade-off, obviously, and if you use tuples everywhere and don't define the correct structures, you are going too far the other way and making your code unreadable. But in cases where use is one-off and easy, they are also easier to write and read more clearly.

+4


source


@Airspeed Velocity gives a really good answer! I just wanted to add how useful Tuples are when used with operators switch

. For example:

let point = (x: 10, y: 5)

switch point {
    case (10, 5):
        println("Point at (10, 5)")

    case (-10...10, 5):
        println("Point where y = 5 and x lies in the range [-10, 10]")

    case (_, 5) :
        println("Point with y = 5")

    case (let x, _) where x % 2 == 0:
        println("Point with x that is a multiple of 2 (x = \(x))")

    default:
        println("A Point")
}

      



Obviously this is not the example you are actually using, but I think it demonstrates some of the capabilities of Tuples.

Apple. Swift Programming Language discusses more about Tuples, here's a link if you haven't seen it already: https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/ doc / uid / TP40014097-CH5-ID309

+3


source







All Articles