0

I have the following code as an extension to AttributedString:

func setBold() -> AttributedString {
    var newAS = self
    for run in runs {
        if let font = run.font { newAS[run.range].font = font.bold() }
        else { // assume NSFont
            let uiFont = run.font ?? UIFont()
            newAS[run.range].font = uiFont.bold()
        }
    }
    return newAS
}

And it works fine but I really don't understand why run.font can be nil in the line after the

for run in runs { 

and

run.font ?? UIFont()

returns a UIFont that is the one stored in the string AttributeContainer not UIFont(). Can anybody explain what's happening? By the way I have an extension of UIFont with the func bold() that is not shown here.

I stumbled onto this by accident trying to extract the CTFont (UIFont) from the attributes and I'm pleased, but surprised it works.

Joseph Levy
  • 157
  • 8

0 Answers0