Now I read Apple documentation about Core Text and I have one problem in understanding:
CTFontSymbolicTraits
conforms to OptionSet
. And CTFontStylisticClass
can be obtained via classMaskTrait
option in CTFontStylisticClass
.
Am I understand right that classMaskTrait
option can includes all CTFontStylisticClass
-options?. For example, if I want to detect sansSerifClass
option in CTFontStylisticClass
:
CTFontStylisticClass(rawValue: CTFontGetSymbolicTraits(font).rawValue).contains(.sansSerifClass)
is it right example checking?
To understand these constants, let's look at the
CTFontStylisticClass
documentation:To verify, let's look at the
kCTFontClassMaskTrait
documentation. If you set the language to Objective-C, the documentation shows the definitions ofkCTFontClassMaskTrait
:So it's just defined as another constant, which has all the same words in a different order. Ha ha, Apple, you're hilarious.
Okay, let's look at the
kCTFontTraitClassMask
documentation. Again, if you set the language to Objective-C, you can see the definition of the constant:Indeed,
15U
is four consecutive 1 bits, and it's shifted left by some amount. This is typical of a “mask”: it defines a subset of the bits in a binary word.To convert a
CTFontSymbolicTraits
to aCTFontStylisticClass
, we need to use the mask to select just those bits from theCTFontSymbolicTraits
raw value, and use the result as the raw value of aCTFontStylisticClass
. We can do the selection by using the bitwise operator&
, or by using theOptionSet
methodintersection
.What we really want, in Swift, is a method on
CTFontSymbolicTraits
that extracts aCTFontStylisticClass
. So let's write an extension:Let's test it:
Output: