Swift 结构继承默认值

Swift Struct Inheritance defaults

我想使用 struct 为我的 iOS 应用程序创建模型,据我所知这是做事的合适方式。我有以下内容:

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
}

考虑到您有一套固定的锻炼类型,完全取消协议会更简单:

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

如果其中一种类型需要多个关联值,您可以选择引入另一个 struct 来保存多个值。示例:

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
    }
}