After updating my xcode to run swift 2 it gives me these two errors which i struggle to solve.
Error 1 Cannot subscript a value of type '[String : AnyObject]?' with an index of type 'String'
Code
let image : UIImage = editingInfo[UIImagePickerControllerOriginalImage] as! UIImage
Error 2 Initializer for conditional binding must have Optional type, not 'UIImage'
Code
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)
}
})
})
}
Best Answer
Following code ...
... is going to crash if there's no
UIImagePickerControllerOriginalImage
key or if it's not an image.From where you did get
editingInfo
? BecauseimagePickerController:didFinishPickingImage:editingInfo:
is not available in Swift. You should useoptional func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
.Your second error on the following line ...
... is caused by
let image: UIImage = ...
line. Yourimage
is ofUIImage
type, notUIImage?
. Thus it's not optional and you can't use it inif let constImage = image
. Must beUIImage?
if you want to use it in this way. BTW there's not need to uselet image: UIImage = ...
,let image = ...
is enough, because compiler can infer variable type from your statement.Rewrite it to something like this.
Following part ...
... does this ...
info
dictionary forUIImagePickerControllerOriginalImage
key? if no,else {}
statement is executed,UIImage
? if no,else {}
statement is executed,info
successfully casted toUIImage
and stored inimage
,else {}
statement is not executed and our function continues.Safe way how to get a value from dictionary of some type when dictionary value type is
AnyObject
for example.