Reputation: 341
I have string name which seems to be an optional name. I need to set that to the textlabel. But this somehow does not seem to work as in the UI the text is not set. when I print out the string unwrapped it looks fine. But when I set the string unwrapped to the uitextlabel.text and print that one out, it seems to be not good as still the keyword optional appears. How can I assign this string unwrapped to the uitextlabel.text correctly?
var name : String?
override func viewDidLoad() {
super.viewDidLoad()
print("School detail view loaded and print address")
let rect = view.bounds
//set header and footer
// schoolNameLabel.text = "set value 1"
// print(schoolNameLabel.text )
if let unwrapped = self.name {
print("print unwrapped")
print(unwrapped)
schoolNameLabel.text = unwrapped
print("print label.text")
print(schoolNameLabel.text)
}
Output on console:
print unwrapped
Milner college
print label.text
Optional("Milner college")
Upvotes: 1
Views: 1109
Reputation: 3317
print(schoolNameLabel.text!) //add this ! optional sign.. becuase that textfiled text value may be null
Upvotes: 0
Reputation: 47896
You have no need to do it. I assume your schoolNameLabel
is a UILabel
.
The property text
of UILabel
is declared as:
var text: String?
So, any non-Optional String
is automatically converted to String?
. Although print
always encloses the actual content with "Optional(" & ")" for non-nil values, UILabel
shows it's actual content without "Optional".
And if "shows nothing when nil
" is what you want, you have no need to unwrap String?
.
Just assign self.name
to schoolNameLabel.text
directly:
schoolNameLabel.text = self.name
It never crashes your app, and just "shows nothing", even if self.name
is nil
.
Upvotes: 2
Reputation: 2685
if let unwrapped = self.name! {
try to save it in unwrapped really as unwrapped so don't miss "!"
Upvotes: 1