nc14
nc14

Reputation: 559

Functions inside Structs - no accessible initialisers error Swift

Following loads of advice from SO in building my first app, I have 2 structs.... 1 for a "WorkoutExercise" and one for a "WorkoutExerciseGenerator".

I'm trying to test out my generator but I'm getting a no accessible initialisers error...

Here's struct 1 :

struct WorkoutExercise {

    let name : String
    let reps : Int

}

Here's struct 2, with a little test and print at the bottom (which doesn't work) :

struct WorkoutExerciseGenerator {

    let name: String
    let maxReps: Int

    func generate() -> WorkoutExercise {
        return WorkoutExercise(
            name: name,
            reps: Int(arc4random_uniform(UInt32(maxReps))))
    }

var test = WorkoutExerciseGenerator(name: "squat", maxReps: 10)

    print (test.generate())
}

My thinking here (following a bit of research here https://www.natashatherobot.com/mutating-functions-swift-structs/) is that I'm correctly inserting the parameters for the generator ("squat" and "maxReps:10") so not sure why this wouldn't work? (In this case generating squat + a random number of reps < 10 from "var = test").

After this I'm going to try use an array of exercise names/max rep values to store all my exercises and randomly grab 3 - 6 exercises to create a completely random workout but I think (hopefully) I can work that out if i get this bit

Upvotes: 0

Views: 43

Answers (1)

Lukas W&#252;rzburger
Lukas W&#252;rzburger

Reputation: 6683

Move the test variable and the print statement out of the struct.

struct WorkoutExerciseGenerator {
    let name: String
    let maxReps: Int

    func generate() -> WorkoutExercise {
        return WorkoutExercise(
            name: name,
            reps: Int(arc4random_uniform(UInt32(maxReps))))
    }
}

var test = WorkoutExerciseGenerator(name: "squat", maxReps: 10)
print (test.generate())

Upvotes: 2

Related Questions