Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shimming in Swift

Tags:

macos

ios

swift

According to Apple engineer Elizabeth Reid "shimming" is when you use conditional compilation to reuse code between iOS and OS X. For example:

#if TARGET_OS_IPHONE
@import UIKit;
#define BaseView UIView
#else
@import AppKit;
#define BaseView NSView
#endif

@interface MyView : BaseView

@end

In the WWDC 2014 session Sharing code between iOS and OS X she also states:

If you literally translate how you would shim with Objective-C, this will not compile in Swift.

There are ways to shim your code in Swift.

But it gets more complicated than your basic conditional compilation that we can use in Objective-C.

So, which are the ways to "shim your code" in Swift?

like image 648
hpique Avatar asked Jun 25 '14 08:06

hpique


1 Answers

that would look like this in Swift:

#if os(iOS)
    import UIKit
    typealias BaseClass = UIView
    #else
    import AppKit
    typealias BaseClass = NSView
#endif

//

class MyClass : BaseClass {

    // ...

}
like image 67
holex Avatar answered Oct 05 '22 12:10

holex