ios - 使用 switch 语句创建泛型函数,该函数根据传入参数的类型执行不同的代码

标签 ios swift generics

目前我有一个函数接受 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/

相关文章:

ios - iOS如何每分钟一分钟调用一次方法

ios - 在聊天应用程序中使用带有 contentoffset 的 uitableview 进行延迟加载

ios - 无法获取 Facebook 用户信息(生日、工作、教育程度)

仅由特定类实现的 Swift 协议(protocol)

ios - 为什么我的 xcode 项目构建在模拟器上而不是 xcode 项目中的设备?

ios - JavaFX WebView - 如何捕获 URL 加载?

swift - 惰性初始化和保留周期

swift - 在 swift 中设置一个泛型类作为委托(delegate)

reactjs - 为什么 typescript 不能确保在 React 中添加额外属性的通用高阶组件中的类型安全?

java - 使用通用 Comparable<T> 数据在 Java 中实现二叉树?