Reputation: 12208
Whats the reason UIButton's titleLabel is optional?
Is it safe to implicitly unwrapped this optional by placing an exclamation mark? If not, what is the case when titleLabel is nil?
BTW, I use UIButton.titleLabel
to change UILabel properties which are not directly accessible from UIButton, for example to change font or to have multiline label.
Upvotes: 2
Views: 974
Reputation: 2638
Best practice is not to force unwrap, but you can pretty much guarantee a UIButton.titleLabel
exists when you need it. I'm not 100% sure of the syntax but it's some form of lazy loading that isn't lazy var titleLabel:UILabel = {}()
Personally I'd say if you're concerned about unwrapping I'd use guard
or if let
guard let label = myButton.titleLabel else {return}
label.font = .systemFontOfSize(10.0)
if let label = myButton.titleLabel { label.font = .systemFontOfSize(10.0) }
Upvotes: 1
Reputation: 7903
Because a Button can be without any Title
assigned to it. Sometimes only Image is required.
Hence in certain case when you'll try to access the Button's Title, without assigning one, the app might crash.
Upvotes: 1