When building a command line tool in Swift 3, I need to prompt the user for keyboard input. How would I go about asking a user for their input (e.g the users name)?
Asked
Active
Viewed 1.3k times
2 Answers
6
readline()
is available since at least Swift 2 and is still available in Swift 3 (Xcode 8 Beta 1):
print("Please enter your name: ", terminator: "")
let name = readLine()!

Code Different
- 90,614
- 16
- 144
- 163
1
This is subject to change as Swift 3 is a moving target, but here is a basic example to prompt a user for their input.
import Foundation
func input() -> String {
let keyboard = FileHandle.standardInput()
let inputData = keyboard.availableData
return NSString(data: inputData, encoding: String.Encoding.utf8.rawValue) as! String
}
print("Please enter your name:")
var name = input()
print("\(name)")

Jason M.
- 563
- 1
- 5
- 10
-
Note that with your solution, `name` will contain a trailing newline character. – Martin R Jun 16 '16 at 12:25
-