David Seek David Seek - 29 days ago 8
iOS Question

Why is the font optional?

I have created a struct to have my fonts pre cached available globally:

struct Fonts {
static let avenirRegular = UIFont(name: "AvenirNextCondensed-Regular", size: 14.0)
}


Usage...:

xy.font = Fonts.avenirRegular


It tells me, that my constant is an Optional.


Value of optional type 'UIFont?' not unwrapped; did you mean to use '!' or '?'?


Why is it an optional? Is there a chance that
AvenirNextCondensed-Regular
is not available on every iOS devices? Help is very appreciated.

Answer

The initializer you are using for UIFont is return optional UIFont? object ie the reason you are getting that suggestion for wrapping optional.

init?(name fontName: String, size fontSize: CGFloat)

Check Apple Documentation of UIFont for more details.