将枚举与开关结合使用时,您可以将关联值绑定(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/