Swift - 在 switch 语句中绑定(bind)泛型参数

标签 swift generics switch-statement

将枚举与开关结合使用时,您可以将关联值绑定(bind)到变量。例如:

let x: Int? = 5

switch x {
case .some(let wrapped):
    print(wrapped) //Assosiated value bound to "wrapped"
case .none:
    print("nil")
}

有没有类似的方法绑定(bind)泛型类型参数?这是我正在寻找的语义类型:

func foo(_ arg: T) {
    switch arg {
    case array as Array<let X>:
        print("The argument is an array of \(X)")
    default:
        print("The argument is not an array")
    }
}

最佳答案

您想检查参数是否为数组?试试这个:

func foo<T>(arr: Array<T>) {
    print("argument is array of \(T.self)")

    switch T.self {
        case is Int.Type:
            print("integer array")
        default:
            print("Unknown type or empty")
    }
}

然后你可以只传递数组作为参数而无需无用的检查。

关于Swift - 在 switch 语句中绑定(bind)泛型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39755395/

相关文章:

swift:使用字符串

ios - SpriteKit + Swift 中的多点触控手势识别

c# - Java:创建一个类型为类型参数的对象

c - SDCC编译器switch语句,ack : section for?是什么

javascript - 联合类型的变量导致 switch 语句中的错误

java - 具有多个值的开关大小写

Swift:即使将动态设置为 false, Sprite 节点在碰撞期间仍然是动态的?

ios - Swift 中的委托(delegate)方法, fatal error

kotlin - 暂停直到 StateFlow 达到所需状态之一并返回结果

泛型:抽象类和子类型