Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use the appropriate color class for the current platform?

Tags:

swift

I'm trying to share my Scene Kit code across iOS and OS X, but the API calls that accept colors (and images) take either UIColor/UIImage or NSColor/NSImage depending on the platform. How do I create the right class in Swift without duplicating the code?

like image 940
alltom Avatar asked Jun 08 '14 17:06

alltom


1 Answers

Use conditional compilation and type aliases:

#if os(OSX)
    typealias Color = NSColor
    typealias Image = NSImage
#else
    typealias Color = UIColor
    typealias Image = UIImage
#endif

Then use Color instead of UIColor or NSColor:

self.gameView!.backgroundColor = Color(red: 0, green: 0.2, blue: 0.5, alpha: 1)

Edit 2016-01-17: As DDPWNAGE noted above, Apple has created SKColor with basically the same definition.

like image 91
alltom Avatar answered Oct 15 '22 16:10

alltom