Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tuple with `let` or `var`

Tags:

swift

tuples

Let's say I have something like this:

func myFunc() -> (Any, Any)? {...}

func anotherFunc() {
    if var (a, b) = myFunc() {
        // a is mutated and accessed; b is accessed, but not mutated
        a = b
    }
}

I need var for the tuple as a is mutated, but Xcode complains that "bwas never mutated, consider using let" - which is a somewhat reasonable argument, but I can't really define the tuple as (var, let).

I guess I could use index to access the two elements instead of declaring them, circumventing this issue. But is there a better way?

like image 436
Stephenye Avatar asked May 17 '17 18:05

Stephenye


People also ask

What is tuple in Swift with example?

Swift 4 also introduces Tuples type, which are used to group multiple values in a single compound Value. The values in a tuple can be of any type, and do not need to be of same type. For example, ("Tutorials Point", 123) is a tuple with two values, one of string Type, and other is integer type. It is a legal command.

Is tuple value type Swift?

Types in Swift fall into one of two categories: first, “value types”, where each instance keeps a unique copy of its data, usually defined as a struct, enum, or tuple. The second, “reference types”, where instances share a single copy of the data, and the type is usually defined as a class.

What are tuples Swift 5?

Tuples in Swift occupy the space between dictionaries and structures: they hold very specific types of data (like a struct) but can be created on the fly (like dictionaries). They are commonly used to return multiple values from a function call.

How do you initialize a tuple in Swift?

You can declare a tuple like any other variable or constant. To initialize it you will need a another tuple or a tuple literal. A tuple literal is a list of values separated by commas between a pair of parentheses. You can use the dot notation to change the values from a tuple if it's declared as a variable.


1 Answers

If you use pattern matching (i.e with if case), then you can use the tuple binding pattern, which allows you to annotate the mutability of the bindings separately:

if case (var a, let b)? = myFunc() {
    a = b
}

This also uses the optional pattern x? in order to unwrap the result of myFunc(), given that we're now using pattern matching instead of optional binding.

like image 143
Hamish Avatar answered Oct 21 '22 22:10

Hamish