Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Declaring empty tuples

Tags:

ios

swift

tuples

What's the correct way to declare an empty tuple?

  • For Arrays: var myArr : [String] = []
  • For tuples: var myTuple: (key: String, val: Int) = () ?

Is there a correct way to achieve this?

like image 778
user2134466 Avatar asked Oct 27 '15 00:10

user2134466


People also ask

How do you declare a tuple in Swift?

In order to create a tuple, first declare a tuple in Swift, we declare a constant or a variable in our code and type the data directly into the circular brackets separated with a comma. Below is the basic structure of a tuple where data1, data2, data3,……,dataN can all be of the same or distinct data type.

Are tuples hashable Swift?

The reason that tuples cannot be used as keys (or specifically, are not hashable ) is because they are not strictly immutable. If you define it using let , it is immutable, but if you define it using var , it is not.

Are tuples reference types 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.


1 Answers

There's no such thing as an "unfilled" tuple value. In other words you don't create an empty tuple and then add values to it later. It's important to remember that tuples aren't collections like Array or Dictionary. Tuples are structured types. For example, you can't iterate through a tuple with a for loop. In your example, myTuple is a single value that happens to contain a String and an Int.

A tuple is like an on-demand unnamed structure, such as the following struct but if it were possible for it to be unnamed:

struct MyStruct {
    let key: String
    let val: Int
}

If you want to model a missing tuple value, you should make the type of the entire tuple optional. For example:

var myTuple: (key: String, val: Int)? = nil
like image 50
Jack Lawrence Avatar answered Oct 11 '22 00:10

Jack Lawrence