clearlight
clearlight

Reputation: 12625

UITextView *font* property is an optional in iOS 9. Is it nil by default?

Apparently iOS 9 changed the UITextView.font property to be a Swift optional type. Does that imply the font property could be be nil on a new UITextView object (meaning it has to be tested for nil)?

If the font property on a newly construct UITextView object is nil, does that imply that UITextView will use default system font, or choose a user designated default font somehow?

Upvotes: 4

Views: 1179

Answers (2)

vacawama
vacawama

Reputation: 154711

Yes, the font property can be nil. I just tried this in a Playground in Xcode 7.0.1 (Swift 2.0):

let view = UITextView(frame: CGRectMake(0,0,100,100))
print(view.font)  // "nil\n"
if (view.font == nil) {
    print("it is nil")  // "it is nil\n"
}

But, surprisingly it doesn't crash when you force unwrap it! (Edit: Read on, this isn't actually the case).

let font = view.font!
print(font.description)

Output:

font-family: "Helvetica"; font-weight: normal; font-style: normal; font-size: 12.00pt

The same behavior was observed in the iOS 9 Simulator.


Playground showing above experiment

Update

From @MartinR's observation in the comments, I was assigning to view.text before unwrapping the view.font which caused it to be assigned the default font value.

So, the answer to the original question is yes, it can be nil and shouldn't be force unwrapped without testing.

Upvotes: 1

Mundi
Mundi

Reputation: 80271

Self explanatory:

import UIKit

let textView = UITextView()
let font  = textView.font
// let fontUnwrapped = textView.font! // crashes
textView.text = "hello"
let fontUnwrapped = textView.font! // <UICTFont: 0x7fbb8c917180> font-family: "Helvetica"; ...

Upvotes: 3

Related Questions