简体   繁体   English

是否可以在同一条件语句中使用可选绑定中的变量?

[英]Is it possible to use the variable from an optional binding within the same conditional statement?

if let popupButton = result?.control as? NSPopUpButto {
    if popupButton.numberOfItems <= 1 {
        // blahblah
    }
}

I want to avoid the double nested if. 我想避免双嵌套if。

if let popupButton = result?.control as? NSPopUpButton && popupButton.numberOfItems <= 1 {}

but I get the unresolved identifier compiler error if I do that. 但是如果这样做,我会得到unresolved identifier编译器错误。

Is there any way to make this condition on one line? 有什么办法可以使这一条件成为一行? Or because I'm using an optional binding, am I forced to make a nested if here? 还是因为我使用的是可选绑定, if在这里,我是否被迫嵌套?

You can do it this way: 您可以这样操作:

if let popupButton = result?.control as? NSPopUpButton, popupButton.numberOfItems <= 1 {
    //blahblah
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Swift中使用具有相同变量名的可选绑定 - Using Optional Binding with the Same Variable Name in Swift 在Swift中的条件语句中为可选的新变量赋值的原因 - Reason for assigning optional to new variable in conditional statement in Swift 如何在准备中使用switch语句中的可选绑定(segue :) - How to use optional binding in switch statement in prepare(segue:) 在Swift中为同一个变量使用weak和optional是多余的吗? - Is it redundant in Swift to use weak and optional for the same variable? 如何在三元条件运算符中使用 Optional 变量? - How do you use the Optional variable in a ternary conditional operator? 用于条件绑定的Swift Initializer必须具有Optional类型,如果使用if let语句,则不能为&#39;Bool&#39;错误 - Swift Initializer for conditional binding must have Optional type, not 'Bool' error with if let statement 将if语句更改为guard会抛出此错误。 条件绑定的初始化程序必须具有可选类型,而不是&#39;(Bool,String)&#39; - Changing an if statement to guard throws this error. Initializer for conditional binding must have Optional type, not '(Bool, String)' 如何在 SwiftUI 中使用带有绑定参数的可选 @State 变量 - How to use optional @State variable with binding parameter in SwiftUI 为什么使用可选绑定? - Why use optional binding? 从 Swift 中的 if 条件中更改变量的值 - Change the value of a variable from within a if conditional in Swift
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM