目前我有一个函数接受 2 个泛型,并基于这些泛型做一些事情:
func drawPath <T, U>(from: T, to: U) {
switch (from, to) {
case is JMapWaypoint, is JMapWaypoint:
print("map")
case is JMapDestination, is JMapDestination:
print("destination")
default:
print("default")
}
}
问题是,在案例行上(例如案例是 JMapDestination,是 JMapDestination:),我收到警告:
Case will never be executed Cast from '(T, U)' to unrelated type'JMapDestination' always fails
如果参数是通用的,难道我不能传递任何东西吗?我不知道它为什么会发出这些警告。
最佳答案
在 switch case 中,,
实际上表示“或”。例如:
let a = 1
switch a {
case 1, 3, 7:
print("xxx") // this will be run if a is 1 or 3 or 7
default: break
}
所以你的 的 switch case 是 JMapWaypoint,是 JMapWaypoint
意思是“(from, to)
is of type JMapWaypoint
or ( from, to)
是 JMapWaypoint
类型”。嗯,(from, to)
是一个元组,所以它永远不可能是 JMapWaypoint
类型。
你应该写:
case is (JMapWaypoint, JMapWaypoint):
相反。
但无论如何,这看起来像是在滥用泛型。如果您的方法仅适用于两种类型,则根据定义它不是通用的...您应该只创建 2 个 drawPath
重载。
关于ios - 使用 switch 语句创建泛型函数,该函数根据传入参数的类型执行不同的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59524530/