Swift: Tuplized If-Lets

Ages ago, I put together a solution for tuplizing if-lets. Today, I finally got to give them a workout. Here’s what they looks like in practice. Before interpolating the cubic Bezier curve in the path element, I perform an if-let across four different optional values. If any are nil, the entire if-let fails and the statement shortcuts, just like a default if-let construct would.

case kCGPathElementAddCurveToPoint.value:
    if let (currentPoint, point, controlPoint1, 
        controlPoint2) = tupled(current?.point, element.point, 
        element.controlPoint1, element.controlPoint2) {
        for index in 1..<numberOfBezierSamples {
            let percent = CGFloat(index) / CGFloat(numberOfBezierSamples)
            let newpoint = CubicBezierPoint(percent, currentPoint, 
                controlPoint1, controlPoint2, point)
            results += [newpoint]
        }
        results += [point]
        current = element
    }
break;

Kevin Ballard helped me figure out the details of the solution. You can examine the source in this gist. Let me know if you find it at all useful.

Update: Yes, in Swift 1.2 you can combine if-let clauses with multiple tests as I described in this post. Here’s an example:

if let x = x, let y = y, let z = z {
    println("All Okay")
} else {
    println("At least one nil")
}

Comments are closed.