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

SOLVED: Day 11 - Access Control Test questions - Syntax confusion

Forums > 100 Days of SwiftUI

There's a line of code on question 9/12 where a custom initializer is written for a struct

init(staff: String...) {

What does the ellipsis (three dots) mean in this case?

I understand that it's a function called init that accepts a single parameter (of type String), which it will name staff. But what does the ... change about this line?

Thanks in advance for the knowledge!

   

Dylan wants to know what the ellipses do in a struct initializer!

What do the ellipsis (three dots) mean in this case?

Most times when you initialize a struct, you know how many variables you need to properly form it. For example an address struct will only have ONE postal code.

Variadic Parameters

However, there are times when you might initialize a struct variable with any number of values. For example, how many students in a maths class? Well, it's different for each maths class isn't it?

Paste the following code into Playgrounds and explore the variations.

// Paste into Playgrounds.
// Dylan! You ARE using Playgrounds, right?!
struct MathsClass {
    var students: [String]  // An array of Students
    init(newStudents: String ...) {  // Not sure how many students will be added?
        students = newStudents // Populate the students var
    }
}

// Initialize the algebra class with five students.
let algebra = MathsClass(newStudents: "Andrew", "Charles", "Anne", "William", "Edward")

// Initialize the calculus class with two students
let calculus = MathsClass(newStudents: "Galileo", "Newton")

algebra.students   // Show the students in the algebra class
calculus.students  // Show the students in the calculus class

In many languages these are called Variadic Parameters. See-> Variadic Parameters

1      

What an excellent answer. Thank you very much Obelix.

   

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.