簡體   English   中英

無法強制打開非可選類型“ 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 letmap if let有用,如果您只是想做某事然后繼續。 map是否有用,如果您需要傳遞UIImage? 周圍並稍后使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM