xcode 从 Swift 3 命令行工具获取用户输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37858809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get user input from Swift 3 command line tool
提问by Jason M.
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)?
在 Swift 3 中构建命令行工具时,我需要提示用户进行键盘输入。我将如何询问用户的输入(例如用户名)?
回答by Code Different
readline()
is available since at least Swift 2 and is still available in Swift 3 (Xcode 8 Beta 1):
readline()
至少从 Swift 2 开始可用,并且在 Swift 3 (Xcode 8 Beta 1) 中仍然可用:
print("Please enter your name: ", terminator: "")
let name = readLine()!
回答by Jason M.
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.
由于 Swift 3 是一个移动目标,这可能会发生变化,但这里是一个提示用户输入的基本示例。
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)")