我正在尝试将字符串分配给标签,如下所示:
self.MsgBlock4.text = "\(wsQAshowTagArray![0]["MsgBlock4"]!)"
但它显示标签Optional(James)
如何删除Optional()?
数组中的Dictionary来自这里:
self.wsQAshowTag(Int(barcode)!, completion: { wsQAshowTagArray in
})
以下是方法:
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()
}
答案 0 :(得分:2)
由于这些是可选项且类型可以是AnyObject
,因此可选的链接/向下转换以及使用nil合并运算符提供默认值似乎是最安全的方法。如果您希望该项目为String
:
self.MsgBlock4.text = (wsQAshowTagArray?[0]["MsgBlock4"] as? String) ?? ""
或者我想对于符合CustomStringConvertible
的任何类型,您都可以使用其description
self.MsgBlock4.text = (wsQAshowTagArray?[0]["MsgBlock4"] as? CustomStringConvertible)?.description ?? ""