【问题标题】:Make a function parameter be of a protocol type that also conforms to a protocol使函数参数成为也符合协议的协议类型
【发布时间】:2019-06-25 17:13:59
【问题描述】:

我想创建一个接受协议类型参数的函数,并确保该协议类型也符合另一种协议类型。有没有办法我可以做到这一点?还是我必须从根本上重新考虑我的方法?

例子:

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

【问题讨论】:

    标签: swift generics enums swift-protocols


    【解决方案1】:

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

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

    【讨论】:

    • 为什么不简单地func enumFunc&lt;T: CaseIterable &amp; MyProtocol&gt;(_ myEnum: T.Type) {
    • @LeoDabus 你是对的,那更简单,更新我的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-03
    • 2019-11-23
    • 1970-01-01
    • 2014-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多