Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
字符串在Swift中仍然是可选的_Swift - Fatal编程技术网

字符串在Swift中仍然是可选的

字符串在Swift中仍然是可选的,swift,Swift,我正在尝试将字符串指定给标签,如下所示: self.MsgBlock4.text = "\(wsQAshowTagArray![0]["MsgBlock4"]!)" 但是它显示的标签类似于soOptional(James)如何删除Optional() 数组中的字典来自这里: self.wsQAshowTag(Int(barcode)!, completion: { wsQAshowTagArray in }) 方法如下: func wsQAshowTag(tag: Int, complet

我正在尝试将字符串指定给标签,如下所示:

self.MsgBlock4.text = "\(wsQAshowTagArray![0]["MsgBlock4"]!)"
但是它显示的标签类似于so
Optional(James)
如何删除Optional()

数组中的字典来自这里:

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()
    }

由于这些是可选的,并且类型可以是
AnyObject
,因此使用nil coalescing操作符进行可选的链接/向下转换并提供默认值似乎是最安全的方法。如果您希望项目为
字符串

self.MsgBlock4.text = (wsQAshowTagArray?[0]["MsgBlock4"] as? String) ?? ""
或者我想对于任何符合
CustomStringConvertible
的类型,您都可以使用其
说明

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

wsQAshowTagArray的类型是什么?您应该再打开一次结果。尝试将此
完成(结果)
更改为
完成(结果!)
。或者将
completion:([AnyObject]?->Void))
更改为
completion:([AnyObject]!->Void))
不要将数组设置为可选数组。@totoajax这不起作用…optional()仍然出现,我尝试了两种解决方案。不要使用字符串插值–直接指定字符串,问题就会出现。你也是。