我该如何编写一个接受泛型类型参数,但根据泛型对象的类型返回不同类型的函数? [英] 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?

查看:659
本文介绍了我该如何编写一个接受泛型类型参数,但根据泛型对象的类型返回不同类型的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在swift3中编写一个基本的插值函数.不过,我有很多错误.显然,这不是使用泛型的正确方法,但是也许我对它们的应用有基本的误解?

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'
}

推荐答案

当您要对几种不同类型执行相同的操作时,泛型函数很有用.基本上就是这里的东西.问题是您没有为您关心的两种类型定义操作,即CGPointCGRect.

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
}

这篇关于我该如何编写一个接受泛型类型参数,但根据泛型对象的类型返回不同类型的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆