为什么我无法传递可选值(?)来获取图片网址?

时间:2016-08-08 10:16:29

标签: swift xcode cocoa-touch

self.imgView .sd_setImageWithURL(NSURL(string: dictData["image"] as? String))

你好我正在使用swift,我想从dictData获取图像URL,但是当我写这行时

dictData["image"] as? String

它给出了Value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?这样的错误,当我点击错误时,它会改善我的代码行

dictData["image"] as! String

为什么会这样?我想知道背后的原因。

3 个答案:

答案 0 :(得分:2)

这意味着dictData["image"] as? String是可选的。 NSURL(string)采用非可选参数。为此,您必须打开可选项。 dictData["image"] as! String是强制解包,这意味着,如果dictData["image"]nil,或者无法转换为字符串,则您的应用会崩溃。我鼓励您使用以下代码

if let image = dictData["image"] as? String {
        self.imgView .sd_setImageWithURL(NSURL(string: image))
} else {
        print("failed to cast to String")
}

答案 1 :(得分:2)

首先,你的dictData是一个字典应该初始化为

var dictData: Dictionary<String, AnyObject>

或您可以使用新的[KeyType: ValueType]注释代替Dictionary<KeyType, ValueType>

if let url = dictData["image"] as? String {
    // no error
}

答案 2 :(得分:1)

NSURL初始化程序仅接受非可选值。当您进行投射dictData["image"] as? String时,它可能会失败并返回nil

您需要做的是确保只有在有对象时才初始化URL:

if let url = dictData["image"] as? String {
    self.imgView.sd_setImageWithURL(NSURL(string: url))
}
相关问题