Swift Struct Inheritance defaults

I would like to create my models for my iOS app using struct as I understand it is the appropriate way to do things. I have the following:

protocol Exercise: Identifiable {
    var id: UUID { get }
    var name: String { get }
    var type: ExerciseType { get }

}

enum ExerciseType {
    case duration
    case reps
    case rest
}

extension Exercise {
    var id: UUID { UUID() }
}

struct DurationExercise: Exercise {
    let name: String
    let durationInSeconds: Int
    let type: ExerciseType = .duration
    
}

struct RepetionsExercise: Exercise {
    let name: String
    let reps: Int
    let type: ExerciseType = .reps
}

struct RestExercise: Exercise {
    let name: String
    let durationInSeconds: Int
    let type: ExerciseType = .rest
}
  • Is this extending the proper way to initialize the id: UUID using protocol + structs?

  • Is there a way where I don't have to specify the name: String in every struct that inherits Exercise?

  • Or if I want to do something like I should just use class?


Solution 1:

Considering that you have a fixed set of exercise types, it would be simpler to eliminate the protocol entirely:

struct Exercise: Identifiable {
    var id: UUID
    var name: String
    var type: ExerciseType
    
    enum ExerciseType {
        case duration(TimeInterval)
        case reps(Int)
        case rest(TimeInterval)
    }
}

If you need multiple associated values for one of the types, you might choose to introduce another struct to hold the multiple values. Example:

struct Exercise: Identifiable {
    var id: UUID
    var name: String
    var type: ExerciseType
    
    enum ExerciseType {
        case duration(TimeInterval)
        case reps(Reps)
        case rest(TimeInterval)
    }
    
    struct Reps {
        var sets: Int
        var repsPerSet: Int
    }
}