A_toaster
A_toaster

Reputation: 1288

When trying to set the text of a UILabel, the result is always 'Optional("0.0")'

I have a UILabel which is part of a [UILabel] array, I am trying to set the text of the UILabel in the following way:

yLabel[0].text = "\(yMaxValue)"

But the result is always 0.0. When I run

println(yLabel[0].text)

The result is Optional("0.0"). Is this because the UILabel is part of an array? How can I set the text of a UILabel that is part of an array?

EDIT: Screenshot of the issue, the output from println(test.text) is Optional("0.0") Screenshot

yLabels are created in this line:

private var yLabels: [UILabel] = [UILabel](count: 5, repeatedValue: UILabel())

Upvotes: 0

Views: 1063

Answers (3)

David Hoelzer
David Hoelzer

Reputation: 16381

The reason is that it is an optional value. If you are sure that it will always have content, try:

println(ylabel[0].text!)

Look at the Apple docs for more information.

Upvotes: 0

rdelmar
rdelmar

Reputation: 104092

The problem is the way you create your array; you're not adding 5 different labels, you're adding 5 of the same label, so the label ends up with whatever value you set last (yMinValue). Create your array like so, and it should work (you should also have the "!" after text like others have pointed out),

private var yLabel = [UILabel(), UILabel(), UILabel(), UILabel(), UILabel()]

Upvotes: 4

Will Richardson
Will Richardson

Reputation: 7970

This code should work, the most likely thing is that yMaxValue is always 0.0 for some unrelated reason.

When you get the text from the label it is wrapped in an optional because the value can be nil. To unwrap it when you print it use: println(ylabel[0].text!).

Upvotes: 0

Related Questions