Why is the font optional?

I created a structure so that my fonts are pre-cached globally:

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

Using...

 xy.font = Fonts.avenirRegular 

He tells me that my constant is optional.

The value of the optional type 'UIFont?' does not unfold; you wanted to use '!' or '?'?

Why is this optional? Is it likely that AvenirNextCondensed-Regular not available on all iOS devices? Help is much appreciated.

+6
source share
3 answers

UIFont initializer you use for UIFont return an optional UIFont? object UIFont? , that is, the reason you receive this offer for optional packaging.

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

Learn more about Apple UIFont Documentation .

+3
source

β€œoptional” here means that the problem is that the font may not exist (even if we know it), and you must recognize it by making it optional, you tell the compiler that I know that the font is not part of your library but I'm sure he is.

+5
source

Just use a power sweep to prevent this:

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

Source: https://habr.com/ru/post/1012097/


All Articles