gpt4 book ai didi

swift - 使函数参数的协议(protocol)类型也符合协议(protocol)

转载 作者:行者123 更新时间:2023-11-30 10:41:12 25 4
gpt4 key购买 nike

我想创建一个接受协议(protocol)类型参数的函数,并确保该协议(protocol)类型也符合另一个协议(protocol)类型。我有办法做到这一点吗?或者我是否必须从根本上重新考虑我的方法?

示例:

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

最佳答案

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

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

关于swift - 使函数参数的协议(protocol)类型也符合协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56759024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com