Articles, podcasts and news about Swift development, by John Sundell.

Making UIImage macOS compatible

Published on 04 Oct 2017

Here's an easy way to make iOS model code that uses UIImage macOS compatible - like me and Gui Rambo discussed on the podcast:

// Either put this in a separate file that you only include in your macOS target or wrap the code in #if os(macOS) / #endif

import Cocoa

// Step 1: Typealias UIImage to NSImage
typealias UIImage = NSImage

// Step 2: You might want to add these APIs that UIImage has but NSImage doesn't.
extension NSImage {
    var cgImage: CGImage? {
        var proposedRect = CGRect(origin: .zero, size: size)

        return cgImage(forProposedRect: &proposedRect,
                       context: nil,
                       hints: nil)

    convenience init?(named name: String) {
        self.init(named: Name(name))

// Step 3: Profit - you can now make your model code that uses UIImage cross-platform!
struct User {
    let name: String
    let profileImage: UIImage

Support Swift by Sundell by checking out this sponsor:

Genius Scan SDK

Genius Scan SDK: Add a powerful document scanner to any iOS app. Genius Scan’s SDK features advanced image processing that’s the result of over 10 years of research and development and can be fully customized and integrated into your app with just one line of code. Mention Swift by Sundell when requesting a free demo to get a 20% discount on your license for a whole year.