# Playing With Interpolation Functions in Swift

### Follow this short guide to interpolation options for your Swift apps.

· Mobile Zone · Tutorial
Save
3.13K Views One of the subjects I'll be covering in my upcoming book, Core Image for Swift, is custom transitions and, as part of that, I wanted to add different interpolations for the transition. I found a great post, Interpolation Tricks, which beautifully explains different interpolation functions and I thought it would be nice to port some of that code to Swift and create a handy playground to demonstrate them.

So, here for your enjoyment is my Interpolation Playground.

All the different interpolations use a single loop function to draw the graph. This function accepts the interpolation function as an argument which is of type (Double) -> Double.

``````func loop( interpolationFunction: Double -> Double )
{
let n = 50

for i in 0 ..< n
{
let v = Double(i) / Double(n)

let _ = interpolationFunction(v)
}

}``````

The first example is linear interpolation where the call is simply

``````        loop { x in x }
`````` Next is smoothstep where the call is:

``````        loop { x in ((x) * (x) * (3 - 2 * (x))) }

`````` Then onto smootherstep where the call is:

``````        loop { x in ((x) * (x) * (x) * ((x) * ((x) * 6 - 15) + 10)) }

`````` Squared and inverse squared are pretty much as expected:

``````        loop { x in (x * x) }

`````` ``````        loop { x in 1 - (1 - x) * (1 - x) }

`````` Now we start to get funky with Catmull-Rom interpolation - try playing with the q and t values in the playground!

``````
func catmullRom(t: Double, _ p0: Double, _ p1: Double, _ p2: Double, _ p3: Double) -> Double
{
return 0.5 * (
(2 * p1) +
(-p0 + p2) * t +
(2 * p0 - 5 * p1 + 4 * p2 - p3) * t * t +
(-p0 + 3 * p1 - 3 * p2 + p3) * t * t * t
)
}

let q = -15.0
let t = 7.5

loop { x in catmullRom(x, q, 0.0, 1.0, t) }

`````` There are also two elastic interpolations - in and out. The original code comes from Robert Penner in this post with a refactor from Josh on Design in this post.

For elastic ease in, the code is:

`````` func elasticIn(x: Double, p: Double = 0.2) -> Double
{
return pow(2, 10 * (x - 1)) * sin((x - p/4) * (2 * M_PI) / p) + 1
}

loop { x in elasticIn(x) }
`````` Ease out is almost the same code:

``````func elasticOut(x: Double, p: Double = 0.2) -> Double
{
return pow(2, -10 * x) * sin((x - p/4) * (2 * M_PI) / p) + 1
}

loop { x in elasticOut(x) }`````` This playground is available at my GitHub repository here. Xcode doesn't seem to support source control for playgrounds, so you'll need to download the zip file.

For additional functions, Robert Penner's Easing.as ActionScript code has loads of great examples and is available at his repo here.

Topics:
swift

Published at DZone with permission of Simon Gladman, DZone MVB.

Opinions expressed by DZone contributors are their own.