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

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

Forums > 100 Days of SwiftUI

@Dylan  

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!

1      

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

2      

@Dylan  

What an excellent answer. Thank you very much Obelix.

1      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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.