2017-03-04 19 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

看起來非常好。我會盡快嘗試。 –