swift - 在 swift 中执行 while == nil 最惯用的方法是什么?

标签 swift while-loop null idioms

这是我在 swift Tic Tac Toe 项目中的一段代码。

var inputTuple = readPositionsFromUser()

while inputTuple == nil {
    print()
    print("Pay attention!")
    print()
    sleep(1)
    inputTuple = readPositionsFromUser()
}

let (row, col) = inputTuple!

ReadPositionsFromUser() 要求用户输入行和列,并返回 nil 除非它可以准确解析两个 Ints,而那些 Ints都在井字棋盘的范围内。

我想知道是否有更惯用的方法来做到这一点,因为最后一行的 ! 感觉有点不必要;如果已经达到代码的那个点,那么我知道 InputTuple 不是 nil,因此使用 ! 似乎很愚蠢。

编辑:我觉得我应该澄清一下,这是一个跨平台的命令行应用程序。我没有使用 Cocoa 或类似的东西。

最佳答案

Swift 编译器可能足够聪明(在优化发布版本时)识别 inputTuple 不能在你的最后一条语句中为 nil。

但是如果你想消除它,你可以将循环包装在一个返回非可选元组的函数中。您甚至可以使用内联闭包,如下所示:

let (row, col): (Int, Int) = {
    while true {
        if let inputTuple = readPositionsFromUser() { return inputTuple }
        print("\nPay attention!\n")
        sleep(1)
    }
}()

print("row=\(row) col=\(col)")

关于swift - 在 swift 中执行 while == nil 最惯用的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44618257/

相关文章:

ios - 核心数据: Do we need to re-fetch after every delete?

loops - Netlogo while 循环仅一次

scala - 将嵌套空值转换为数据帧 Spark 内的空字符串

android - 检查列表中每个项目的空值

java - 使用内容值的更新方法

ios - swift fatal error : 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=3840 "Garbage at end."

ios - Swift 2.0 元组模式元素标签必须是 '_'

php - Foreach 和 while 循环打印相同的值

c - 链接列表指针的位置(索引)问题

ios - NMACoreRouter calculateRouteWithStops 无回调(快速)