teko teko - 7 months ago 216
Swift Question

Cannot assign value of type '[String : AnyObject]

I am using Xcode 7 and swift I get this error when run my app in my iPhone:


Cannot assign value of type
[String : AnyObject]
to type
UIImage?



func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
imgview.image = info
[UIImagePickerControllerOriginalImage]as?UIImage;
dismissViewControllerAnimated(true, completion: nil)
}

Answer

The problem is that you cannot split [] operator onto a separate line in Swift: square brackets need to be on the same line as the dictionary being dereferenced. Also don't forget to dismiss and release the picker.

picker.dismissModalViewControllerAnimated(true)
picker.release()
imgview.image = info[UIImagePickerControllerOriginalImage] as UIImage

Since Swift does not use mandatory semicolons to break down statements, you need to pay more attention to what goes onto which line. Your code is interpreted like this:

  • Assign info to imgview.image
  • Cast an array that consists of UIImagePickerControllerOriginalImage to UIImage

Obviously, this is not the effect that you were trying to get. Moving square brackets to the same line as info will fix this problem.