WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

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

   

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.

1      

Save 50% in my Black Friday sale.

SAVE 50% To celebrate WWDC22, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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

Reply to this topic…

You need to create an account or log in to reply.

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.