The best way to describe what I want is by this example:
protocol Lerpable {
// here should be 'lerp<T: Lerpable>(_ x: CGFloat, _ a: T, _ b: T) -> T' function
}
extension CGFloat: Lerpable {}
extension CGPoint: Lerpable {}
extension CGRect: Lerpable {}
func lerp(_ x: CGFloat, _ a: CGFloat, _ b: CGFloat) -> CGFloat {
return a * (1.0 - x) + b * x
}
func lerp(_ x: CGFloat, _ a: CGPoint, _ b: CGPoint) -> CGPoint {
return CGPoint(x: lerp(x, a.x, b.x), y: lerp(x, a.y, b.y))
}
func lerp(_ x: CGFloat, _ a: CGRect, _ b: CGRect) -> CGRect {
return CGRect(x: lerp(x, a.x, b.x), y: lerp(x, a.y, b.y), width: lerp(x, a.width, b.width), height: lerp(x, a.height, b.height))
}
func lerpKeyframes<T: Lerpable>(_ x: CGFloat, array: [T]) -> T? {
if x <= 0 {
return array.first
}
else if x >= (array.count - 1) {
return array.last
}
else {
let leftBound = Int(x)
let fraction = fmod(x, 1.0)
return lerp(fraction, array[leftBound], array[leftBound + 1]) // ERROR here, can't recognize implemented 'lerp' method
}
}
How to write this code, so I could use lerpKeyframes(...)
for CGFloat
, CGPoint
and CGRect
?