Swift泛型和枚举作为数据源

时间:2020-08-19 09:18:10

标签: swift swift-protocols

我有一个视图,该视图显示选项列表,并为用户提供选择其中一个选项的选项。此视图必须可重用,以与多组选项一起使用。我该怎么做。我尝试了以下方法,但是遇到了错误Protocol 'Options' can only be used as a generic constraint because it has Self or associated type requirements,我知道为什么会这样。还有更好的方法吗?

protocol Options: CaseIterable {
    var displayName: String { get }
}

enum MyOptions: Options {
    case hello
    case mello
    case fello
    
    static var allCases: [MyOptions] {
        [.hello,.mello]
    }
    
    var displayName: String {
        "hello"
    }
}

/// This is just for testing

func testContains(option: Options, options: [Options]) -> Bool {
    true
}

print(testContains(option: MyOptions.fello, options: MyOptions.allCases))

2 个答案:

答案 0 :(得分:0)

您需要将类型限制为testContains的{​​{1}}方法更改为通用方法。

Options

答案 1 :(得分:0)

仅将CaseIterable应用于需要它的枚举,而不是将其放在基本协议上。如果必须在基础中使用CaseIterable,那么@DávidPásztor正确地说,您必须使用类型擦除或泛型。

//
// used to be 'protocol Options: CaseIterable {'
//
protocol Options {
    var displayName: String { get }
}

// I just moved CaseIterable down from the base.
enum MyOptions: Options, CaseIterable {
    case hello
    case mello
    case fello

    static var allCases: [MyOptions] {
        [.hello,.mello]
    }

    var displayName: String {
        "hello"
    }
}

/// This now compiles and runs
func testContains(option: Options, options: [Options]) -> Bool {
    true
}

print(testContains(option: MyOptions.fello, options: MyOptions.allCases))