使功能参数为也符合协议的协议类型

时间:2019-06-25 17:13:59

标签: swift generics enums swift-protocols

我想创建一个带有协议类型参数的函数,并确保该协议类型也符合另一种协议类型。有办法吗?还是我必须从根本上重新考虑我的方法?

示例:

// This doesn't extend CaseIterable itself because I would like to use it as a concrete type and not just a generic constraint
protocol MyProtocol {
    /*some protocol stuff*/
}

enum myEnum: MyProtocol, CaseIterable {
    /*some enum stuff*/
}

func<T: CaseIterable>(_ myEnum: MyProtocol.Type) 
where MyProtocol.Type: CaseIterable {
    myEnum.allCases //   <--- This is what I would like to do
}

1 个答案:

答案 0 :(得分:0)

您需要更改函数签名,以将通用类型约束用作输入参数的类型,并将通用类型参数限制为MyProtocolCaseIterable

func enumFunc<T: MyProtocol & CaseIterable>(_ myEnum: T.Type) {
    myEnum.allCases //   <--- This is what I would like to do
}