我想在swift3中編寫一個基本插值函數。不過,我收到了很多錯誤。這顯然不是使用泛型的正確方法,但也許我對它們的應用有一個根本性的誤解。如何編寫一個採用泛型類型參數的函數,但基於泛型對象的類型返回不同的類型?
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'
}
你嘗試的通用方法在http://stackoverflow.com/questions/38652237/how-can-i-handle-different-types-using-generic-type-in建議 - 快捷? –
這個答案只是擴展我所關心的具有內插函數的類的一種更長的方式,這正是我現在正在做的一項權衡措施。它也沒有回答爲什麼我嘗試不起作用的問題。 – GoldenJoe