1

My code was working perfectly with Swift2 and now for some label the variable is displayed but with Optional(....) just before...

Good code on Swift 2

var sstitre1:String!
 print(sstitre1)

There is a perform segue which populate a value to sstitre1.

    var sstitre1:String?

    sstitre1 = json[21].string


 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "hugo"
    {
        if let destinationVC = segue.destination as? MonumentViewController{

            destinationVC.sstitre1 = "\(sstitre1)"

        }

    }
}

With Swift3, i ve get : Optional(.....)

I want to get rid of Optional.

So i have as recommend on several post from stackoverflow, made some code change.

var sstitre1:String!

If let espoir = sstitre1 {
print (espoir)
}

But unfortunately it still displays Optional....

Pretty weird ....

Hugo75
  • 249
  • 3
  • 15
  • 1
    Possible duplicate of [Swift 3 incorrect string interpolation with implicitly unwrapped Optionals](http://stackoverflow.com/questions/39537177/swift-3-incorrect-string-interpolation-with-implicitly-unwrapped-optionals) – vadian Nov 25 '16 at 19:13
  • Yes it s same issue but i didnt get a proper way to deal with it. – Hugo75 Nov 25 '16 at 19:14
  • How are you assigning `sstitre1`? Sounds like you're baking the `"Optional(...)"` into the string itself. – Hamish Nov 25 '16 at 19:14
  • The value coming from a previous screen via performsegue – Hugo75 Nov 25 '16 at 19:14
  • @Hugo75 Then please show us that code. – Hamish Nov 25 '16 at 19:15
  • As suggested in the linked article you have explicitly to unwrap the optional : `print(sstitre1!)`. However the best way to get rid of that problems is to use non-optionals. – vadian Nov 25 '16 at 19:15
  • @vadian : error: cannot force unwrap value of non optional type string – Hugo75 Nov 25 '16 at 19:17
  • Then the issue comes from an earlier String Interpolation of an optional somewhere else – vadian Nov 25 '16 at 19:18
  • @Hamish, you will find additional code – Hugo75 Nov 25 '16 at 19:31

1 Answers1

1

In the line

destinationVC.sstitre1 = "\(sstitre1)"

always a literal string "Optional(foo)" is assigned to destinationVC.sstitre1 assuming the variable contains "foo"

The solution is to remove the String Interpolation

destinationVC.sstitre1 = sstitre1

PS: You should really use more descriptive variable names

vadian
  • 274,689
  • 30
  • 353
  • 361