gpt4 book ai didi

swift - UIGraphicsGetImageFromCurrentImageContext() 给了我一个强制解包选项的链式 react ,我在 Swift 中不想要

转载 作者:搜寻专家 更新时间:2023-11-01 07:01:51 25 4
gpt4 key购买 nike

我对在 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()!

关于创建 CIImageCIFilter 和文件 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.ciImagenil 并且您想尝试从 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com