我試圖寫一個類,讓我方便地在兩個值之間的插值。如何在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