Swift: Type Conversions

Yesterday, I stumbled across this write-up by Mikael Konutgan courtesy of a bit of mistaken attribution. It shows you how to implement custom type conversions, enabling you to bridge Swift classes and functions to structs and non-standard classes. This is helpful information for anyone who has struggled with error messages that state some item “is not convertible” to another type.

What caught my eye was tuples-on-demand. With this, you could use tuple assignment to access struct fields in parallel, as in this example:

var myCGRect = CGRectMake(0, 0, 50, 100)
let (_, _, w, h) = myCGRect

This is not built-in behavior. This derives from implementing the following extension. The __conversion() function enables you to convert from the Core Graphics rectangle structure to a Swift-style 4-tuple.

extension CGRect {
    func __conversion() -> (Double, Double, Double, Double) {
        return (self.origin.x, self.origin.y, self.size.width, self.size.height)
    }
}

Even better, you can overload the conversion and allow type inference to determine the return-tuple style you’re looking for:

extension CGRect {
    func __conversion() -> (Double, Double, Double, Double) {
        return (self.origin.x, self.origin.y, self.size.width, self.size.height)
    }
    func __conversion() -> (Double, Double) {
        return (self.size.width, self.size.height)
    }
}

Although Konutgan’s main point is discussing how you can use this approach to connect Swift classes and structures to Cocoa/Touch equivalents, it’s this flexible conversion that really stood out to me. I should add that the built-in conversion items use the @conversion keyword (thanks SH) but that extra notation does not seem to be strictly necessary in my testing.

There are any number of built-in conversion functions that you can inspect using Command-Click.

Finally? This is not the material you thought you were googling for.

 

Comments are closed.