Michael Rader Michael Rader - 1 month ago 6
Swift Question

How do I set a property value of a struct?

To set the value of

multiplier
I thought I use the syntax
threeTimesTable.multiplier = 3
. How is the below working out? It looks like I'm passing an argument to the
struct
and initializing a value, but I don't see an initializer in the class. I'm very confused by what is going on here. Is the argument optional in the
struct
?

struct TimesTable {
let multiplier: Int
subscript(index: Int) -> Int {
return multiplier * index
}
}
let threeTimesTable = TimesTable(multiplier: 3)
print("six times three is \(threeTimesTable[6])")
// Prints "six times three is 18"

Answer

Because this is a struct, Swift provides a default memberwise initializer (classes don't have this feature). From the Swift book:

Memberwise Initializers for Structure Types

All structures have an automatically-generated memberwise initializer, which you can use to initialize the member properties of new structure instances. Initial values for the properties of the new instance can be passed to the memberwise initializer by name

In your case, this translates to:

struct TimesTable {
    let multiplier: Int

    // This is automatically provided by the compiler
    init(multiplier: Int) {
        self.multiplier = multiplier
    }

    subscript(index: Int) -> Int {
        return multiplier * index
    }
}
Comments