swift - 代码清理 Swift

标签 swift option-type

我在 AppDelegate 中有一个名为 inScreenshotmode 的变量:

#if DEBUG
var inScreenshotMode: Bool {
    return UserDefaults.standard.bool(forKey: "abc")
}
#else // Release
let inScreenshotMode = false
#endif

那么我该如何优化下面的代码呢?

    let totalValue = appDelegate?.inScreenshotMode == true ? basicInfo.value : configuration.value

如果我这样做

let totalValue = appDelegate?.inScreenshotMode ? basicInfo.value : configuration.value

我收到错误:

Value of optional type 'Bool?' not unwrapped; did you mean to use '!' or '?'? Replace 'appDelegate?.inScreenshotMode' with '(appDelegate?.inScreenshotMode)!'

什么是最好的解决方案?

最佳答案

根据您对 appDelegate 的声明,您似乎将其声明为可选(不确定这是什么原因),您面临的是 Optional Chaining :

Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil. If the optional contains a value, the property, method, or subscript call succeeds; if the optional is nil, the property, method, or subscript call returns nil. Multiple queries can be chained together, and the entire chain fails gracefully if any link in the chain is nil.

这意味着你必须确保 appDelegate 不是 nil 而不是 (appDelegate?.inScreenshotMode)!,我建议做可选绑定(bind):

if let unwrappedAppDelegate = appDelegate {
    let totalValue = unwrappedAppDelegate.inScreenshotMode ? basicInfo.value : configuration.value
}

关于swift - 代码清理 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49295163/

相关文章:

ios - CoreGraphics 和上下文中的旋转和渐变

ios - 使用 iOS Swift 将带有额外参数的文件上传到 AWS S3

swift - 从 Vapor 2.0 中的请求对象获取 IP 地址?

java - 如果不为空 - java 8 风格

Java Stream 映射到多个属性

swift - 转义闭包捕获 'inout' 参数

ios - swift - 来自预填充 SQLite 的 CoreData

ios - 设置 UITableView 的属性时,意外发现 nil 将解包 Optional 值

java - 检查流的任何元素是否不存在

java - 有没有方便的从Optional到Stream的映射方法?