UIFont Class Crashed app in Swift

1.1k views Asked by At

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?

4

There are 4 answers

1
Justin Rose On BEST ANSWER

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!

1
Ankit Sachan On

Its should be called like this

let fonts =  FontHelper().defaultFont(mySize)
0
pableiros On

If you add custom fonts manually to your project, you need to register the fonts before use it in runtime:

func loadFont(withName fontName: String) {
    guard let fontURL = Bundle.main.url(forResource: fontName, withExtension: "ttf"),
          let fontData = try? Data(contentsOf: fontURL) as CFData,
          let provider = CGDataProvider(data: fontData),
          let font = CGFont(provider) else { return }
    CTFontManagerRegisterGraphicsFont(font, nil)
}

// For example, this array need to contain the fonts filenames without extension.
let fontNames = ["Roboto-Black", "Roboto-Regular", "Roboto-Bold"]

for fontName in fontNames {
    loadFont(withName: fontName)
}
0
Sapana Ranipa On

When u work with UIFont(name:"HelveticaCE-Regular", size:14.0)

I believe iOS requires the PostScript name for a font when using fontWithName: size:, which you can find/verify by opening the font in Apple's Font Book and typing command+I.

Maybe this helps you.