2017-03-04 28 views
-1

我不明白为什么编译器不会允许我使用这个非常简单的赋值,因为我while循环语句:斯威夫特重复使用时的readLine

// 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代码显示为全灰色,就像它不再被识别)。

谢谢

+0

它是如何不工作? “寻求调试帮助的问题(”为什么不是这个代码工作?“)必须包含所需的行为,特定的问题或错误以及在问题本身中重现问题所需的最短代码。没有明确问题陈述的问题对其他读者没有用处 – EmilioPelaez

+0

对不起,我很忙。稍后我会编辑它。 –

+0

你的代码不会编译,因为在Swift中(与C相反),赋值语句不返回值。但是你期望*会发生什么?循环的目的是什么?因为'readLine()'只在文件结束时返回nil,所以你无法继续。 –

回答

2
  1. 这不是有效的银行代码
  2. 即使它运行时,如果我选择这不是你的行动清单上的项目?

试试这个:

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 
+0

看起来非常好。我会尽快尝试。 –