[swift-users] reading keyboard input from xcode playgroud

Zhao Xin owenzx at gmail.com
Tue Sep 20 08:46:22 CDT 2016


I test you code in command line `swiftc main.swift` and in macOS Command
Line Tool app.

Here is the main.swift:

import Foundation


import Foundation


func input() -> String {

    let keyboard  = FileHandle.standardInput

    let inputData = keyboard.availableData

    let strData   = String(data: inputData, encoding: .utf8)

    return strData!

}


func write(_ txt: String) {

    print(txt, terminator: "")

}


func read() -> String {

    let c = CharacterSet.whitespacesAndNewlines

    return input().trimmingCharacters(in: c)

}


/* main program */


write("Enter your name: ")

let s = read()

print("You name is \(s)")


It turns out that the input request was ran before the `write("Enter your
name: ")`. I don't why. Maybe it is a bug?


Here is my output in terminal:


$ swiftc main.swift

$ ./main

abc

Enter your name: You name is abc

$


As you can see, the program asked me to input my name before it showed the
notification. In playground, the situation is alike.


However, if the code is running as a command line tool, created by Xcode ->
Create a new project -> macOS, command line tool, everything works fine.


Zhaoxin

On Sun, Sep 18, 2016 at 9:16 PM, Mr Bee via swift-users <
swift-users at swift.org> wrote:

> Hi all,
>
> Another question. I used to use this snippet to read keyboard input from
> XCode's Playground. And it used to work very well. Today, I just updated my
> XCode to v.8 and Swift v.3. After a little bit modification here and there
> due to Swift 3 incompatibility, I got this code compiled without error. But
> it doesn't work. No keyboard input is taken. It just stucks.
>
> Here's the code:
>
> import Foundation
>
> func input() -> String {
>   let keyboard  = FileHandle.standardInput
>   let inputData = keyboard.availableData
>   let encoding  = String.Encoding(rawValue: String.Encoding.utf8.rawValue)
>   let strData   = String(data: inputData, encoding: encoding)
>   return strData! as String
> }
>
> func write(_ txt: String) {
>   print(txt, terminator: "")
> }
>
> func read() -> String {
>   let c = CharacterSet.whitespacesAndNewlines
>   return input().trimmingCharacters(in: c)
> }
>
> /* main program */
>
> write("Enter your name: ")
> let s = read()
>
> So, does anyone know how to make it works (again)? Thank you.
>
> Regards,
>
> –Mr Bee
>
>
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160920/b11b67b3/attachment.html>


More information about the swift-users mailing list