尝试使用下面的NSURL类时出错,下面的代码实际上是试图将我从Facebook拉入的图像存储到imageView中.错误如下:
value of optional type 'NSURL?' not unwrapped,did you mean to use '!' or '?'
不知道为什么会这样,帮忙!
import UIKit class ViewController: UIViewController { @IBOutlet weak var myImage: UIImageView! override func viewDidLoad() { super.viewDidLoad() let myProfilePictureURL = NSURL(string: "http://graph.facebook.com/bobdylan/picture") let imageData = NSData(contentsOfURL: myProfilePictureURL) self.myImage.image = UIImage(data: imageData) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
解决方法
你正在调用的NSURL构造函数有这个签名:
convenience init?(string URLString: String)
?表示构造函数可能不返回值,因此它被视为可选.
NSData构造函数也是如此:
init?(contentsOfURL url: NSURL)
let myProfilePictureURL = NSURL(string: "http://graph.facebook.com/bobdylan/picture") let imageData = NSData(contentsOfURL: myProfilePictureURL!) self.myImage.image = UIImage(data: imageData!)
最好的解决方案是检查(解包)这些选项,即使您确定它们包含值!
你可以在这里找到更多关于期权的信息:link to official Apple documentation.