Tuple in Swift

Tram Ho

Two years ago, when I started with iOS, I didn’t know what tuples were, why and where I would use them. Over the next few weeks, I realized that I was really using them everywhere, I just didn’t know it.

Small example:

Sometimes even you accidentally run func with nothing, and the compiler says nothing about that. The compiler return () has an empty tuple.

Swift is mapping to return void in tuples.

Tuples does not have a definitive, unclear definition, but is easy to create and easy to use.

However, it also has disadvantages, they cannot implement methods and protocols. And like every other set, you can’t change its type.

Here is a basic example:

This is an advanced topic with closures:

Even if you cannot add methods to the tuple, you can add closures

To be honest, I don’t remember even doing this in real situations, but I know this will work, but there’s a problem with closures and tuples together. You cannot access some elements in this way:

So where are they most commonly used?

As in other articles that mention this topic, I would say the same:

When you need a func will return many value types.

But what that means, in fact. Perhaps you will not write anything like this:

But in at least 50% of apps, you will have something like this:

This is great, but swift has an even better way to do this

In summary, in most cases, you will use tuple as the return type of the call API, escaping closure.

Typealias and tuples:

Tuples are great for this function, writing functions with data sets as return types is much easier if you implement them like this.

Tuples can be very long and can be repeated many times in the same method.

For example:

Practical examples:

Something else I can mention is an optional tuple:

Finally, interviewing tips can be done with tuple and you will definitely get more points ? We all know about fizzbuzz testing. You will get a series of numbers and you will need to check which number is divisible by the other two numbers, in most cases 3 and 5.

Conclusion

I hope you like this, if there is anything unclear about this, or you have something great or really advanced on this subject please comment.

Source: Medium

Share the news now

Source : Viblo