我试图写一个类,让我方便地在两个值之间的插值。如何在swift中使用泛型类型处理不同的类型?
class Interpolation
{
class func interpolate<T>(from: T, to: T, progress: CGFloat) -> T
{
// Safety
assert(progress >= 0 && progress <= 1, "Invalid progress value: \(progress)")
if let a = from as? CGFloat, let b = to as? CGFloat
{
}
if let a = from as? CGPoint, let b = to as? CGPoint
{
}
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 from
}
}
不幸的是,它给了我在return returnRect
错误:无法转换类型的返回式“的CGRect”返回类型“T”。也许我不懂如何使用泛型...我只想有一个函数可以处理各种类型之间的插值,而不是像func interpolate(from: Int, to: Int)
,func interpolate(from: CGPoint, to: CGPoint)
等一堆函数。
(1)这是更好地使用协议来实现。 (2)只需使用[dclelland/Lerp](https://github.com/dclelland/Lerp)而不是自己写。 – kennytm