'UIImage?' 无法转换为 'UIImage' 问题 swift 4

'UIImage?' is not convertible to 'UIImage' issue in swift 4

我正在尝试实现图像选择器。在委托方法中,我收到以下错误。

这是我写的代码

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    var image = info[.editedImage] as? UIImage
    if image == nil {
        image = info[.originalImage] as? UIImage
    }

    simpleImagePicker!.dismiss(animated: true)
}

我用 Swift 5 试过了,它运行正常,没有错误。但问题在于 Swift 4.

如何解决这个问题?有什么解决办法吗?

UIImagePickerControllerDelegate 签名对于不同的 Swift 版本是不同的。您正在使用 Swift 4.2 及更高版本的方法,这与 Swift 4.0.

有很大不同

Swift 4.0:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let editedImage = info[UIImagePickerControllerEditedImage] as? UIImage {

    } else if let originalimage = info[UIImagePickerControllerOriginalImage] as? UIImage {

    }
}

Swift 4.2 & Swift 5:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    if let image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {

    } else if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {

    } else {
        print("Something went wrong")
    }
}

所以,检查正确的 swift 版本并遵循正确的方法!

I tried this using Swift 5 and it is working without error. But the issue is with Swift 4.

首先,如果您使用的是 Xcode 10.x,我强烈建议您执行 Swift 5 更新。忘记 Swift 4 并保持更新。

其次,这是 Swift 5 上的正确 UIImagePickerControllerDelegate 实现:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
        // do stuff with your original image...

    } else if let image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
        // do something with your edited image...
    }
    dismiss(animated: true, completion: nil)
}


无论如何,如果你想坚持 Swift 4,这是要使用的 ImagePicker 委托函数:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        if let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage {
            // do stuff with your image
        } else if let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage {
            // do stuff with your image
        }
        dismiss(animated:true, completion: nil)
}

主要问题是 Swift 4 中没有 UIImagePickerController.InfoKey。 编译器无法定义此类型,从而导致错误 如果使用 [String: Any] 字典为 swift 4 使用正确的签名,错误将消失