How can I write a function that takes generic type arguments, but returns a different type based on what the generic object's type is? [duplicate]

廉价感情. 提交于 2019-12-12 03:44:16

问题


I'm trying to write a basic interpolation function in swift3. I get a lot of errors, though. This is obviously not the right way to use generics, but maybe I have a fundamental misunderstanding of their application?

class func interpolate<T>(from: T, to: T, progress: CGFloat) -> T
{
    // Safety
    assert(progress >= 0 && progress <= 1, "Invalid progress value: \(progress)")

    if let from = from as? CGFloat, let to = to as? CGFloat
    {
        return from + (to - from) * progress // No + candidates produce the expected contextual result type 'T'
    }
    if let from = from as? CGPoint, let to = to as? CGPoint
    {
        var returnPoint = CGPoint()
        returnPoint.x     = from.x + (to.x-from.x) * progress
        returnPoint.y     = from.y + (to.y-from.y) * progress
        return returnPoint // Cannot convert return expression of type 'CGPoint' to return type 'T'
    }
    if let from = from as? CGRect, let to = to as? CGRect
    {
        var returnRect = CGRect()
        returnRect.origin.x     = from.origin.x + (to.origin.x-from.origin.x) * progress
        returnRect.origin.y     = from.origin.y + (to.origin.y-from.origin.y) * progress
        returnRect.size.width   = from.size.width + (to.size.width-from.size.width) * progress
        returnRect.size.height  = from.size.height + (to.size.height-from.size.height) * progress
        return returnRect // Cannot convert return expression of type 'CGRect' to return type 'T'
    }

    return nil // Nil is incompatible with return type 'T'
}

回答1:


A generic function is useful when you have the same operations to perform on several different types. That's basically what you have here. The problem is that you don't have the operations defined for two of the types that you care about, namely CGPoint and CGRect.

If you create separate functions to add, subtract, and multiply those types, you can make this generic function work. It would be simplified to

class func interpolate<T>(from: T, to: T, progress: CGFloat) -> T
{
    // Safety
    assert(0.0...1.0 ~= progress, "Invalid progress value: \(progress)")

    return from + (to - from) * progress
}


来源:https://stackoverflow.com/questions/38687228/how-can-i-write-a-function-that-takes-generic-type-arguments-but-returns-a-diff

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!