Tips for Cross Platform Development

Become a Subscriber

Create type aliases so that more code can be shared

If you’re using basic SDK classes and methods such as UIColor you’ll find that the mac SDK equivalentNSColor has many of the same methods, but that your shared code will error out as NSColor is not available on iOS and vice versa. A quick and dirty little hack for this is to simply create a CrossPlatform.swift file that you can quickly conditionally include SDK’s and do a typealias of the classes you are using. The small snippet below is useful, as from this point on, you could use Color.init(red: 68/255, green: 85/255, blue: 166/255, alpha: 1) in your code and it will work on both platforms.

#if os(macOS)
  import AppKit
  typealias Color = NSColor
  typealias BezierPath = NSBezierPath
  import UIKit
  typealias Color = UIColor
  typealias BezierPath = UIBezierPath