Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Universal class for Mac OS and iOS [duplicate]

Tags:

swift

I want to create a class for a Mac OS- and a iOS-App. Unfortunately, I can't use NSColor for iOS and no UIColor for Mac OS.

Actually I have the following code:

#if os(iOS)
    func myFunc(color: UIColor?) {
        self.myFuncX(color)
    }
#elseif os(OSX)
    func myFunc(color: NSColor?) {
        self.myFuncX(color)
    }
#endif

private func myFuncX(color: AnyObject?) {
    #if os(iOS)
        myColor = color as! UIColor
    #elseif os(OSX)
        myColor = color as! NSColor
    #endif
}

Is there any better way?

like image 705
Lupurus Avatar asked Apr 22 '15 19:04

Lupurus


1 Answers

You should be able to use typealias for the color class, like this:

#if os(iOS)
    typealias XColor = UIColor
#elseif os(OSX)
    typealias XColor = NSColor
#endif

func myFunc(color: XColor?) {
    self.myFuncX(color)
}

The idea is to limit conditional compile to a type definition for XColor, and then using that type alias in place of UIColor or NSColor, as required on the particular system.

like image 79
Sergey Kalinichenko Avatar answered Oct 31 '22 06:10

Sergey Kalinichenko