RT

Lerp.swift - Linear Interpolation in Swift

Below are four lerp functions that I implemented while working on a side project.

The first function is templated to work with any type that conforms to BinaryFloatingPoint (Float, Double, CGFloat, TimeInterval, etc.). The other three functions operate on Core Graphics structs (CGPoint, CGSize, and CGRect).

//
//  Lerp.swift
//
//  Written by Ramon Torres
//  Placed under public domain.
//

import Foundation

// swiftlint:disable identifier_name

@inline(__always)
func lerp<V: BinaryFloatingPoint, T: BinaryFloatingPoint>(_ v0: V, _ v1: V, _ t: T) -> V {
  return v0 + V(t) * (v1 - v0);
}

@inline(__always)
func lerp<T: BinaryFloatingPoint>(_ v0: CGPoint, _ v1: CGPoint, _ t: T) -> CGPoint {
    return CGPoint(
        x: lerp(v0.x, v1.x, t),
        y: lerp(v0.y, v1.y, t)
    )
}

@inline(__always)
func lerp<T: BinaryFloatingPoint>(_ v0: CGSize, _ v1: CGSize, _ t: T) -> CGSize {
    return CGSize(
        width: lerp(v0.width, v1.width, t),
        height: lerp(v0.height, v1.height, t)
    )
}

@inline(__always)
func lerp<T: BinaryFloatingPoint>(_ v0: CGRect, _ v1: CGRect, _ t: T) -> CGRect {
    return CGRect(
        origin: lerp(v0.origin, v1.origin , t),
        size: lerp(v0.size, v1.size , t)
    )
}

// swiftlint:enable identifier_name