Spekham2013
Spekham2013

Reputation: 113

Unwrapping a optional in swift which is an optional but swift doesn't know its a optional

I'm working on an app to convert model paint color's. I just got coreData to work and now I ran into a different problem.

let colorL: String = String(color.valueForKey("revell"))
    let AmountL: String = String(color.valueForKey("filled"))
    
    print(colorL)
    print(AmountL)
    
    cell.ColorLabel.text = colorL
    cell.AmountLabel.text = AmountL

This is my code for the tableview. and my console output is this

Optional(68)
Optional(g)

and so the problem is if you haven't guessed yet that I need to unwrap a optional that cannot be unwrapped because swift doesn't know it is a optional and I keep on getting a error that I can't unwrap a non-optional.

Upvotes: 0

Views: 76

Answers (2)

Shemona Puri
Shemona Puri

Reputation: 811

    let colorL: String = (color.valueForKey("revell")?.description)!
    let AmountL: String = (color.valueForKey("filled")?.description)!

    print(colorL)
    print(AmountL)

    ColorLabel.text = colorL
    AmountLabel.text = AmountL

Upvotes: 0

keithbhunter
keithbhunter

Reputation: 12324

valueForKey returns an optional (AnyObject? to be specific). Unwrap that and then build a string with it.

if let value = color.valueForKey("revell") as? /* Some Type */ {
    let amountL: String = String(value)
    // ...
}

Upvotes: 1

Related Questions