我在 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/