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 "b
was 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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With