UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Day 7: Returning multiple values from functions - can I iterate over a tuple like an array?

Forums > 100 Days of SwiftUI

Hi, first post here. I’m on Day 7 of the revised 100 Days of SwiftUI journey. This day is about returning multiple values from functions. Tuples were introduced for the first time.

Q1: Are tuples a first class complex data type like Arrays, Dictionaries and Sets? Curious to know why they weren’t introduced in earlier days?

Q2: Are tuples in Swift immutable like they are in Python?

Q3: I half expected the discussion on tuples in functions was going to mean I could iterate over a tuple like an array as shown below. But this doesn't seem possible.

Why can this be done with arrays but not tuples?

var tupleList = ("A", 2.9, 10)
for i in tupleList {
    print(i)
 }
 // Error: Type does not conform to protocol sequence

It’s fine to let me know if this is covered in detail in days to come!

Thanks, Anthony

1      

Think of a tuple almost like an anonymous struct. It's not a collection of homogeneous data like an Array, a Dictionary or a Set, it's a structured data type whose members can have differing types. The only real differences between structs and tuples are:

  1. struct types have a name; tuples don't
  2. structs can implement protocols; tuples can't
  3. names for tuple elements are optional; for structs they are mandatory
  4. tuples can be created as ad hoc, on the fly instances; structs have to be predefined as types

To answer the question you posed in the thread title: no, not really.

While technically, you could iterate a tuple using the Mirror API, if you are wanting to iterate you are almost certainly better off using an array or other sequence type that actually is intended for iteration.

As for mutability, you can change the elements of a tuple if it is declared as var but not if it was declared as let. This is just like structs, but tuples don't have the added wrinkle that struct properties can themselves be var or let independent of how the struct variable is declared.

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.