Swift通过提示获取用户输入

时间:2016-02-20 05:22:58

标签: swift command-line

在Swift中,我希望有一个连续的用户输入循环,就像python解释器的工作方式,提示,你输入一行,显示行的结果,然后提示用户再次。到目前为止,这是我的代码:

import Foundation

func input() -> String {
    var keyboard = NSFileHandle.fileHandleWithStandardInput()
    var inputData = keyboard.availableData
    return NSString(data: inputData, encoding: NSUTF8StringEncoding) as! String
}
while true {
    println("Obl>")
    var theInput = input()
    println("\(theInput)")

}

但是,这导致了这样的方案:

Obl>
hello world
hello world
Obl>
yo
yo

我希望它看起来像这样:

Obl> hello world
hello world
Obl> hello
hello

如何实现这一目标?

2 个答案:

答案 0 :(得分:1)

你还在使用Swift 1吗? Swift 2中已弃用println

斯威夫特1:

print("Obl> ")

斯威夫特2:

print("Obl>", terminator: " ")

而不是你的input()函数,你可以使用readLine,这是Swift中的标准函数:

let theInput = readLine()

答案 1 :(得分:0)

/*
For Swift 3
Note I do not claim credit for this, but it does work to prompt for and   retrieve user inputs
*/

import Foundation

print("Please enter your name:")

if let name = readLine() {
    print("Hello, \(name)!")
} else {
    print("Why are you being so coy?")
}

print("TTFN!")
相关问题