Skip to main content
1 / 2
h2so5
  • 4,103
  • 2
  • 16
  • 36

python3のinput()に近いものを実装してみました。

import Foundation

func input(prompt: String = "") -> String {
    print(prompt)
    fflush(__stdoutp)
    let keyboard = NSFileHandle.fileHandleWithStandardInput()
    let inputData = keyboard.availableData
    let charset = NSCharacterSet(charactersInString:"\r\n")
    let str = NSString(data: inputData, encoding:NSUTF8StringEncoding)!
    return str.stringByTrimmingCharactersInSet(charset)
}

println(input(prompt: ">> "))

参考: http://stackoverflow.com/q/24004776/1205869

$ xcrun swift input.swift
>> Hello
Hello
h2so5
  • 4,103
  • 2
  • 16
  • 36