user3110353 user3110353 - 1 year ago 93
Swift Question

UIFont Class Crashed app in Swift

I have a UIFont Class that looks like this:

struct FontHelper {
func defaultFont(size: CGFloat) -> UIFont {
return UIFont(name:"Helvetica", size: size)!

and I call the method like this"

let fonts = FontHelper.defaultFont(12)

However my app crashes with an unexpected found nil while wrapping optional?

Have no idea why?

Answer Source

Since you're adding your own personal functionality to a Type, I think you should use an extension, declare this extension outside of your class:

extension UIFont {
    // You can set a default value for the size if the user doesn't provide one.
    class func defaultFont(size: CGFloat = 12) -> UIFont {
        return UIFont(name:"Helvetica", size: size)!

Now, the UIFont Type has this really cool functionality you just added.

Within your class, call it:

let font = UIFont.defaultFont(12)

I hope you can see the power of extensions here, so take advantage of them in Swift!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download