使用readLine

时间:2017-03-04 15:04:01

标签: 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.description+" ("+action.name+")\n")
    }
} while !(let chosen_action = readLine())

此外,它在Xcode中创建了一个错误(代码显示为灰色,就像它不再被识别一样)。

谢谢

1 个答案:

答案 0 :(得分:2)

  1. 这是无效的Swift代码
  2. 即使它运行,如果我选择一个不在您的行动清单上的项目怎么办?
  3. 试试这个:

    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