我对在 Swift 中使用 UIGraphicsGetImageFromCurrentImageContext()
感到困惑,这让我强制解包它,即使它是用 let
定义的。添加 ?
或 !
会使我的代码看起来很乱,并且让我在它之后更改所有内容。我不想在定义 scaledImage 时要求它。
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let scaledCIImage:CIImage = (scaledImage?.ciImage)! // makes me force upwrap
// gives error 'Value of optional type 'CIFilter?' not unwrapped; did you mean to use '!' or '?'?'
let filter = CIFilter(name: "CIAffineTile", withInputParameters:[kCIInputImageKey:scaledCIImage]).outputImage
最佳答案
有很多合法用途!
如果您知道何时正确使用它。
来自 UIGraphicsGetImageFromCurrentImageContext
的文档:
If the current context is nil or was not created by a call to UIGraphicsBeginImageContext(_:), this function returns nil.
由于您正在使用 UIGraphicsBeginImageContext
并且您当前的上下文不是 nil
,因此 UIGraphicsGetImageFromCurrentImageContext()
不会返回 nil
所以强制解包是安全的。
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()!
关于创建 CIImage
、CIFilter
和文件 CIImage
,使用 if let
安全解包.
if let scaledCIImage = scaledImage.ciImage,
let filter = CIFilter(name: "CIAffineTile", withInputParameters:[kCIInputImageKey:scaledCIImage]),
let outputImage = filter.outputImage {
// Do what you need with outputImage
}
根据您的评论更新:
鉴于 scaledmage.ciImage
是 nil
并且您想尝试从 cgImage
创建一个 CIImage
,您可以将 if let
的链更新为:
if let cgImage = scaledImage.cgImage {
let scaledCIImage = CIImage(cgImage: cgImage)
if let filter = CIFilter(name: "CIAffineTile", withInputParameters:[kCIInputImageKey:scaledCIImage]),
let outputImage = filter.outputImage {
// Do what you need with outputImage
}
}
关于swift - UIGraphicsGetImageFromCurrentImageContext() 给了我一个强制解包选项的链式 react ,我在 Swift 中不想要,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50766671/