更新我的xcode以运行swift 2后,它给了我这两个我很难解决的错误。
错误1 无法下标类型' [String:AnyObject]的值?'索引类型为' String'
代码
let image : UIImage = editingInfo[UIImagePickerControllerOriginalImage] as! UIImage
错误2 条件绑定的初始化程序必须具有可选类型,而不是' UIImage'
代码
if let constImage = image (Error2 display here)
{
let targetWidth = UIScreen.mainScreen().scale * UIScreen.mainScreen().bounds.size.width
let resizedImage = constImage.resize(targetWidth)
picker.dismissViewControllerAnimated(true, completion: {
() -> Void in
NetworkManager.sharedInstance.postImage(resizedImage, completionHandler: {
(error) -> () in
if let constError = error
{
self.showAlert(constError.localizedDescription)
}
})
})
}
答案 0 :(得分:5)
以下代码......
let image : UIImage = editingInfo[UIImagePickerControllerOriginalImage] as! UIImage
如果没有UIImagePickerControllerOriginalImage
密钥或者它不是图像,...会崩溃。
从哪里获得editingInfo
?因为Swift中没有imagePickerController:didFinishPickingImage:editingInfo:
。您应该使用optional func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
。
您在下一行的第二个错误......
if let constImage = image
...由let image: UIImage = ...
行引起。您的image
属于UIImage
类型,而不是UIImage?
。因此,它不是可选的,您无法在if let constImage = image
中使用它。如果您想以这种方式使用它,则必须为UIImage?
。顺便说一下,不需要使用let image: UIImage = ...
,let image = ...
就足够了,因为编译器可以从你的语句中推断变量类型。
将其重写为类似的内容。
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else {
// throw an error, return from your function, whatever
return
}
// from now you can use `image` safely
// it does exist and it's not optional
let targetWidth = UIScreen.mainScreen().scale * UIScreen.mainScreen().bounds.size.width
let resizedImage = image.resize(targetWidth)
picker.dismissViewControllerAnimated(true, completion: {
() -> Void in
NetworkManager.sharedInstance.postImage(resizedImage, completionHandler: {
(error) -> () in
if let constError = error
{
self.showAlert(constError.localizedDescription)
}
})
})
}
以下部分......
guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else {
// throw an error, return from your function, whatever
return
}
......这样做......
info
密钥的UIImagePickerControllerOriginalImage
字典中是否有值?如果否,则执行else {}
语句,UIImage
吗?如果否,则执行else {}
语句,info
成功投放到UIImage
并存储在image
中,else {}
语句未执行且我们的功能仍在继续。当字典值类型为AnyObject
时,如何从某种类型的字典中获取值的安全方法。