4

.I am new to iOS and to Swift In my application I'm trying to print an optional value and it prints "Optional(value of the variable)" How do I remove this word optional

var bDay = StringUtils.convertDateToString(birthDate, format: Constants.BIRTHDAY_FORMAT)
let age = self.clientDetail?.getAge()
println("age.....\(age)")
bDay += "\(age)"

The output in the console is

age.....Optional(29)

I'm trying to assign this variable to a UILabel but on screen it shows up like Sep 17, 1986 Optional(29)

My objective is to remove this optional word and make it appear like Sep 17, 1986(29)

Thanks in advance

Abhilasha
  • 929
  • 1
  • 17
  • 37

1 Answers1

9

Optional chaining is used here:

let age = self.clientDetail?.getAge()

So return of getAge() is optional value. Try optional binding:

if let age = age {
    println("age.....\(age)")
}

or simply unwrap the age with age!, but this will crash your app if age is nil.

vacawama
  • 150,663
  • 30
  • 266
  • 294
Kirsteins
  • 27,065
  • 8
  • 76
  • 78
  • Using the forced unwrapping operator is discouraged without checking for nil first. It causes the app to crash if `age` is nil - I recommend updating your answer with an explicit mention about that – Antonio Nov 04 '14 at 11:17
  • @Antonio It depends on the situation. If they where discouraged in any case the implicitly unwrapped optionals couldn't even be in the language. Sometimes its good to crash early. – Kirsteins Nov 04 '14 at 11:22
  • @Kristeins The updated answer works for me :) – Abhilasha Nov 04 '14 at 11:25
  • @Kirsteins: indiscriminate usage of the forced unwrapping is to be avoided unless for specific needs. There's a reason if `clientDetail` is an optional: because it can be nil. Using `!` prints the correct string **OR** makes the app crash. I am just suggesting you to make that explicit, because it's really bad to misuse it. Once done, I'll remove my downvote – Antonio Nov 04 '14 at 11:28
  • @Antonio If you don't want to unwrap optional without checking for the I guess its best to use optional bidding in every case as its more clearer in intent. – Kirsteins Nov 04 '14 at 11:33
  • @Kirsteins Optional binding is one possible solution. What is important is that a potentially nil expression is guarded against forced unwrapping, whichever method is used to accomplish that. I think it's important to make that clear when answering to questions. – Antonio Nov 04 '14 at 11:40
  • @Kirsteins How do I do optional binding for priceLabel.text = "S \(meal.price)". Meal is a variable, Price a double. – Cons Bulaquena Jul 29 '18 at 19:31