IOSDev IOSDev - 7 months ago 33
Swift Question

Why i am not able to pass optional value ( ? ) for getting image url?

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

Hello I am using swift and i want to get image URL from dictData but when i Write this line

dictData["image"] as? String

it giving error like this Value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'? and when i click on the error its improve my line of code by this

dictData["image"] as! String

why this happened.Please give me any suggestion because i want to know what is the reason behind that.


That means dictData["image"] as? String is an optional. And NSURL(string) takes a non optional parameter. In order to do so you have to unwrap the optional. dictData["image"] as! String is force unwrapping which means, if dictData["image"] is nil or if it fails to cast to String your app will crash. I encourage you to use the following code

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