-4

I am trying to assign a string to a label like so:

self.MsgBlock4.text = "\(wsQAshowTagArray![0]["MsgBlock4"]!)"

But it display the label like so Optional(James) how do I remove the Optional() ?

The Dictionary inside the array comes from here:

self.wsQAshowTag(Int(barcode)!, completion: { wsQAshowTagArray in

})

Here is the method:

func wsQAshowTag(tag: Int, completion: ([AnyObject]? -> Void)) {
        let requestString = NSString(format: "URL?wsQATag=%d", tag) as String
        let url: NSURL! = NSURL(string: requestString)
        let task = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: {
            data, response, error in
            do {
                let result = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as? [AnyObject]
                completion(result)
            }
            catch {
                completion(nil)
            }
        })
        task.resume()
    }
ntoonio
  • 3,024
  • 4
  • 24
  • 28
user979331
  • 11,039
  • 73
  • 223
  • 418
  • what is type of `wsQAshowTagArray`? You should just unwrap the result one more time. – Bryan Chen May 16 '16 at 03:48
  • Try changing this `completion(result)` to `completion(result!)`. Or change `completion: ([AnyObject]? -> Void))` to `completion: ([AnyObject]! -> Void))` – ntoonio May 16 '16 at 07:40
  • Don't make your array an optional. – Eric Aya May 16 '16 at 08:53
  • @totoajax this did not work...Optional() is still appearing, I tried both your solutions. – user979331 May 16 '16 at 14:06
  • Don't use string interpolation – just assign the string directly, and the problem will present itself. You also [shouldn't be force unwrapping](http://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu). – Hamish May 16 '16 at 19:56

1 Answers1

2

Since these are optionals and the type can be AnyObject, optional chaining / downcasting and providing a default value using the nil coalescing operator seem the safest approach. If you're expecting the item to be a String:

self.MsgBlock4.text = (wsQAshowTagArray?[0]["MsgBlock4"] as? String) ?? ""

Or I guess for any type that conforms to CustomStringConvertible you can use its description

self.MsgBlock4.text = (wsQAshowTagArray?[0]["MsgBlock4"] as? CustomStringConvertible)?.description ?? ""
Casey Fleser
  • 5,707
  • 1
  • 32
  • 43