objective-cmacoscocoaswiftnsfont

How do you compare NSFontSymbolicTraits and NSFontBoldTrait in Swift?


I'm trying to bitwise compare NSFontSymbolicTraits and NSFontBoldTrait in Swift.

In Objective-C it'd be done like this:

BOOL isBold = (fontDescriptorSymbolicTraits & UIFontDescriptorTraitBold);

So I'm thinking it should be this in Swift:

let isBold:Bool = font.fontDescriptor.symbolicTraits & NSFontBoldTrait

...However that results in the following error:

Cannot invoke '&' with an argument list of type '(NSFontSymbolicTraits, Int)'

Anyone know what I'm missing? Any help would be greatly appreciated.

Notes:


Solution

  • In Swift, NSFontSymbolicTraits is a type alias for UInt32. So to check for the existence of a particular trait, you need to compare the result of your bitwise & to zero. Unfortunately, the individual constraints have been imported as type Int, so you also need to convert them to the right type:

    let isBold = 0 != (font.fontDescriptor.symbolicTraits & NSFontSymbolicTraits(NSFontBoldTrait))
    

    If you wanted to do this in iOS (instead of OS X), UIFont has a different implementation. UIFontDescriptorSymbolicTraits is a RawOptionSetType, so you compare the result of your & with nil:

    let isBold = nil != (font.fontDescriptor().symbolicTraits & UIFontDescriptorSymbolicTraits.TraitBold)