Josh Weinstein
Josh Weinstein

Reputation: 2968

Swift get user input with prompt

In Swift, I want to have a continous user-input loop, much like how the python interpreter works, where a prompt is made, you type a line, the result of the line is displayed, and then the user is prompted again. This is my code so far:

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)")

}

However, this results in a scheme like this:

Obl>
hello world
hello world
Obl>
yo
yo

What I want it to look like is this:

Obl> hello world
hello world
Obl> hello
hello

How can this be accomplished?

Upvotes: 0

Views: 3949

Answers (2)

NewStacker
NewStacker

Reputation: 1

/*
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!")

Upvotes: 0

Code Different
Code Different

Reputation: 93181

Are you still using Swift 1? println has been deprecated in Swift 2.

Swift 1:

print("Obl> ")

Swift 2:

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

And instead of your input() function, you can just use readLine, which is a standard function in Swift:

let theInput = readLine()

Upvotes: 1

Related Questions