gpt4 book ai didi

swift - 如何在 Swift 中通过实际类型限制 switch case

转载 作者:行者123 更新时间:2023-11-30 12:08:59 24 4
gpt4 key购买 nike

我想将 Swift 枚举中的情况与基于协议(protocol)的关联值进行匹配。具体来说,我想将情况限制为关联值的实际类型,但我不确定这是否可能。

protocol MyProtocol {}

extension Int:MyProtocol {}
extension Double:MyProtocol {}

enum MyEnum {
case something(MyProtocol)
case nothing
}

let somethingInt = .something(10)
let somethingDouble = .something(10.0)

switch somethingInt {
case .something(let aValueInt):
!!! I want to figure out how to limit this case to a double or an int
case .something(let aValueDouble):
!!! I want to figure out how to limit this case to a double or an int
case .nothing:
break
}

最佳答案

下面是一个可以正确编译并运行的示例:

    protocol MyProtocol {}

extension Int:MyProtocol {}
extension Double:MyProtocol {}

enum MyEnum {
case something(MyProtocol)
case nothing
}

let somethingInt = MyEnum.something(10)
let somethingDouble = MyEnum.something(11.0)

switch somethingInt { // and try it with somethingDouble instead
case .something(let aValueInt as Int): print(aValueInt)
case .something(let aValueDouble as Double): print(aValueDouble)
case .something(_): break
case .nothing: break
}

关于swift - 如何在 Swift 中通过实际类型限制 switch case,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46307352/

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