![](/img/trans.png)
[英]Cannot force unwrap value of non-optional type '(UIImagePickerController, [UIImagePickerController.InfoKey : UIImage]) -> ()'
[英]Cannot force unwrap value of non-optional type 'UIImage'
在我的項目中包含以下代碼行。 但是我總是會出錯。 我正在使用Xcode 7.2和iOS 9。
let image: UIImage = UIImage(CGImage:imageRef, scale:originalImage.scale, orientation:originalImage.imageOrientation)!
刪除!
該方法的結果不是可選的-您不需要解開它。
注意:您不需要變量中的: UIImage
-Swift會為您推斷出它的類型。
編輯:如果imageRef
是可選的(來自@chewie的評論)怎么辦?
您有幾種選擇。
1 if let
:
if let imageRef = imageRef {
let image = UIImage(CGImage: imageRef, scale: originalImage.scale, orientation: originalImage.imageOrientation)
// Do something with image here
}
2使用guard
guard let imageRef = imageRef else {
print("Oops, no imageRef - aborting")
return
}
// Do something with image here
let image = UIImage(CGImage: imageRef, scale: originalImage.scale, orientation: originalImage.imageOrientation)
3使用地圖
let image = imageRef.map {
UIImage(CGImage: $0, scale: originalImage.scale, orientation: originalImage.imageOrientation)
}
// Do something with image here, remembering that it's
// optional this time :)
使用哪種選擇是您的選擇,但這是我的經驗法則。
如果您需要做的事情需要映像,請使用guard
並在沒有映像時盡早中止。 通常,這使您的代碼更易於閱讀和理解。
如果您不需要圖像就可以完成操作,請使用if let
或map
。 if let
有用,如果您只是想做某事然后繼續。 map
是否有用,如果您需要傳遞UIImage?
周圍並稍后使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.