如果Swift中有什么更好的chain语法

jtoj6r0c  于 2023-08-02  发布在  Swift
关注(0)|答案(3)|浏览(134)

我想写一个函数,根据子集函数的返回值执行几个子集函数。逻辑是如果funcA被成功执行,则返回否则执行funcB如果funcB被成功执行,则返回否则执行funcC我已经遵循了片段,但想知道swift中是否有更好的语法?

func funcA() -> Bool {
    // Implementation of funcA goes here
    // Replace this with your actual logic for funcA
    return true // Replace 'true' with the actual result of funcA
}

func funcB() -> Bool {
    // Implementation of funcB goes here
    // Replace this with your actual logic for funcB
    return false // Replace 'false' with the actual result of funcB
}

func funcC() {
    // Implementation of funcC goes here
    // Replace this with your actual logic for funcC
    print("Function C executed")
}

func performLogic() {
    let resultA = funcA()
    
    if resultA {
        return // Return early if resultA is true
    }
    
    let resultB = funcB()
    
    if !resultB {
        funcC()
    }
}

performLogic()

字符串

vuktfyat

vuktfyat1#

老实说,你现在的代码可读性很好,我不认为它需要一个“更好”的语法。您可以使语法更短,但这会使其可读性降低。
例如,你可以做(假设你不需要中间结果):

if !funcA() && !funcB() {
    funcC()
}

字符串
这利用了&&是惰性的这一事实。
如果可以更改函数的返回类型,那么将funcC更改为也返回Bool可以做到:

funcA() || funcB() || funcC()


或者,将它们全部更改为返回Void?。不成功时返回nil,否则返回()。这允许您使用??操作符,这是一种常见的习惯用法,用于在出现故障时提供“默认值

funcA() ?? funcB() ?? funcC()


也就是说,返回Void?看起来很奇怪。如果函数实际上返回了一些有意义的值,那么我建议这样做。

jxct1oxe

jxct1oxe2#

最好使用guard_1guard_2

func funcA() -> Bool {
    // Implementation of funcA goes here
    // Replace this with your actual logic for funcA
    return true // Replace 'true' with the actual result of funcA
}

func funcB() -> Bool {
    // Implementation of funcB goes here
    // Replace this with your actual logic for funcB
    return false // Replace 'false' with the actual result of funcB
}

func funcC() {
    // Implementation of funcC goes here
    // Replace this with your actual logic for funcC
    print("Function C executed")
}

func performLogic() {
    guard funcA() else {
        return // Return early if resultA is true
    }
    
    guard !funcB() else {
        funcC()
        return
    }
}

performLogic()

字符串

jdg4fx2g

jdg4fx2g3#

我只在真正需要的时候使用局部作用域变量。这种方法降低了复杂性,并可以使代码更清晰。如果函数的命名是有意义的,那么使用局部作用域变量可能根本就没有必要。
在Swift中实现提前返回,通常使用guard

func performLogic() {
    guard !funcA() else { return }
    guard funcB() else { return }

    funcC()
}

字符串

相关问题