Swift中如何在if语句中结合或条件处理可选类型?
Swift中用if语句实现可选绑定或布尔条件的逻辑
你写的代码无法直接通过编译,因为Swift不允许在||的一侧直接使用可选绑定——可选绑定只能作为if条件的顶层结构,或者在逗号分隔的条件组中(逗号逻辑上等同于&&)。不过完全可以用if语句实现你想要的逻辑,不需要必须使用guard,下面是几种可行的写法:
方法1:嵌套分支(最直观)
把布尔条件和可选绑定的判断拆成嵌套的if分支,逻辑上和你想要的(A && B) || C完全等价:
let isSomeThingTrue = checkSomeThing() if isSomeThingTrue { // do something } else if let someOptional = getSomeOptional(), let anotherOptional = getAnotherOptional(withSomeOptional: someOptional) { // do something with someOptional and anotherOptional } else { // do something else }
方法2:用临时变量存储可选绑定结果
如果需要在do something块中同时使用解包后的变量和布尔条件的状态,可以先把可选绑定的结果存起来,再统一判断:
let isSomeThingTrue = checkSomeThing() var targetSome: SomeType? var targetAnother: AnotherType? // 先尝试解包两个可选 if let tempSome = getSomeOptional(), let tempAnother = getAnotherOptional(withSomeOptional: tempSome) { targetSome = tempSome targetAnother = tempAnother } // 再判断是否满足任一条件 if targetSome != nil && targetAnother != nil || isSomeThingTrue { // 这里可以安全地强制解包,或者再次用if let if let some = targetSome, let another = targetAnother { // 使用解包后的变量 } // do something } else { // do something else }
方法3:立即执行闭包封装可选绑定逻辑
用一个立即执行的闭包来封装可选绑定的逻辑,一次性获取解包结果,写法更紧凑:
let isSomeThingTrue = checkSomeThing() let (someOptional, anotherOptional) = { () -> (SomeType?, AnotherType?) in guard let s = getSomeOptional(), let a = getAnotherOptional(withSomeOptional: s) else { return (nil, nil) } return (s, a) }() if someOptional != nil && anotherOptional != nil || isSomeThingTrue { // 使用解包后的变量 if let s = someOptional, let a = anotherOptional { // do something with s and a } // do something } else { // do something else }
总结:你想要的逻辑完全可以用if语句实现,guard只是可选的写法,并非必须。
内容的提问来源于stack exchange,提问作者Ashish P
相关产品推荐
相关产品推荐

