Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xcode/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
带readLine的Swift repeat while语句_Swift_Xcode - Fatal编程技术网

带readLine的Swift repeat while语句

带readLine的Swift repeat while语句,swift,xcode,Swift,Xcode,我不明白为什么编译器不允许我使用这个相当简单的赋值作为while循环条件: // Get user's input repeat { // displays possible actions print("Select one of the following actions (by writing the text within the parenthesis):\n") for action in actions { print(action.desc

我不明白为什么编译器不允许我使用这个相当简单的赋值作为while循环条件:

// Get user's input
repeat {
    // displays possible actions
    print("Select one of the following actions (by writing the text within the parenthesis):\n")
    for action in actions {
        print(action.description+" ("+action.name+")\n")
    }
} while !(let chosen_action = readLine())
而且,它在Xcode中创建了一个bug(代码看起来都是灰色的,好像再也认不出来了)

多谢各位

  • 这不是有效的Swift代码
  • 即使它运行,如果我选择了一个不在您的操作列表中的项目怎么办

  • 试试这个:

    struct Action {
        var name: String
        var description: String
    }
    let actions = [
        Action(name: "a", description: "Action A"),
        Action(name: "b", description: "Action B")
    ]
    
    var chosen_action: Action?
    repeat {
        print("Select one of the following actions (by writing the text within the parenthesis):")
        for action in actions {
            print(action.description+" ("+action.name+")")
        }
    
        let actionName = readLine()
        chosen_action = actions.first { $0.name == actionName }
    } while chosen_action == nil
    

    它怎么不起作用<代码>寻求调试帮助的问题(“为什么此代码不工作?”)必须包括所需的行为、特定的问题或错误以及在问题本身中重现这些问题所需的最短代码。没有明确问题陈述的问题对其他读者没有用处对不起,我赶时间。稍后我将对其进行编辑。您的代码不会编译,因为在Swift中(与C相反),赋值语句不会返回值。但是你期望发生什么呢?循环的目的是什么?因为
    readLine()
    仅在文件末尾返回nil,然后您无论如何也不能继续。@Martin\r如果用户在没有任何输入的情况下按“enter”键,或者如果我没有得到任何值,则赋值将返回nil,即“将返回*false”