Monday, October 12, 2015

Getting the fontNames from Swift with XCode 7.01

func fontForDisplay(atIndexPath indexPath: NSIndexPath) -> UIFont? {
    if indexPath.section == 0 {
        let familyName = familyNames[indexPath.row]
        let fontName = UIFont.fontNamesForFamilyName(familyName).first as String
        return UIFont(name: fontName, size: cellPointSize)
    } else {
        return nil

The above snippet of code is from
Beginning iPhone Development with Swift Exploring the iOS SDK
I'm trying this on el capitan and xcode 7.01, which now uses swift 2.0

The first issue is that xcode will warn you that 'String?' is not convertible to 'String'
Adding a ! to force cast and will allow the code to run. (append it to either first! or String!)

The next issue is that this is thrown: EXC_BAD_EXCEPTION
Looking at the trace, we can see

familyName = (String) "Bangla Sangam MN"
fontName = (String!) nil

So it appears that we're trying to get the first element of an empty array. I ended up with this solution:

    let fontArray: String? = UIFont.fontNamesForFamilyName(familyName).first
    let fontName = (fontArray != nil) ? fontArray! : ""

Let me know if there is a more idiomatic way of doing this with Swift 2.0

No comments: