创建一个带有 switch 语句的泛型函数,该函数根据参数中传递的类型执行不同的代码



目前我有一个函数,它接受 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:(,我收到警告:

案件永远不会被执行 从"(T, U("转换为不相关的类型"JMapDestination"总是失败

如果参数是通用的,我不应该传递任何东西吗? 我不知道它为什么要发出这些警告。

在开关情况下,,实际上意味着"OR"。例如:

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
}

因此,您的is JMapWaypoint, is JMapWaypoint开关情况表示"(from, to)属于JMapWaypoint类型或(from, to)属于JMapWaypoint类型"。好吧,(from, to)是一个元组,所以它永远不可能是JMapWaypoint型。

你应该写:

case is (JMapWaypoint, JMapWaypoint):

相反。

但无论如何,这似乎是您在滥用泛型。如果您的方法仅适用于两种类型,则根据定义,它不是通用的...您应该只创建 2 个重载drawPath

最新更新