Freelance iOS Developer, Rapidly Aging Punk

Swift Has a Preprocessor

Jan 21, 2015 at 03:21PM

I didn't know Swift had a preprocessor at all. It means you can do things like this:

#if TARGET_OS_MAC
    typealias RAImage = NSImage
    typealias RAFont = NSFont
#elseif TARGET_OS_IPHONE
    typealias RAImage = UIImage
    typealias RAImage = UIFont
#endif

And this:

var image = RAImage()
#if TARGET_OS_IPHONE
    UIGraphicsBeginImageContextWithOptions(textRect.size, false, 0.0)
    text.drawInRect(textRect, withAttributes: textAttributes)
    image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
#elseif TARGET_OS_MAC
    image = RAImage(size: textRect.size)
    image.lockFocus()
    text.drawInRect(textRect, withAttributes: textAttributes)
    image.unlockFocus()
#endif

Pretty cool.