Michael Behan

Follow @mbehan on Micro.blog.

My Swift Extension (Anti?) Pattern

I’ve become aware of how frequently I create extensions in Swift. I previously viewed them as something to use sparingly, like when there was something missing from a built-in type that was needed frequently - but now I regularly write them for once-off use.

This is the example that got me thinking about it today:

extension UInt8 {
    static func entireRange() -> ClosedRange<UInt8> {
        return UInt8.min...UInt8.max
    }
}

Which exists only to be used in this other extension:

extension Data {
    static func randomBytes(size: Int) -> Data {
        var byteArray = [UInt8]()

        for _ in 0..<size {
            byteArray.append(UInt8.random(in: UInt8.entireRange()))
        }

        return Data(byteArray)
    }
}

Which exists to be called once in some test code that will eventually be replaced when working with the actual data.

I leave the extensions in context in the files where they’re being used rather than in a specific file for the extension, or a collection of helpers and I find the resulting code reads wonderfully.