Input from the keyboard in command line application

118,664

Solution 1

I managed to figure it out without dropping down in to C:

My solution is as follows:

func input() -> String {
    var keyboard = NSFileHandle.fileHandleWithStandardInput()
    var inputData = keyboard.availableData
    return NSString(data: inputData, encoding:NSUTF8StringEncoding)!
}

More recent versions of Xcode need an explicit typecast (works in Xcode 6.4):

func input() -> String {
    var keyboard = NSFileHandle.fileHandleWithStandardInput()
    var inputData = keyboard.availableData
    return NSString(data: inputData, encoding:NSUTF8StringEncoding)! as String
}

Solution 2

The correct way to do this is to use readLine, from the Swift Standard Library.

Example:

let response = readLine()

Will give you an Optional value containing the entered text.

Solution 3

It's actually not that easy, you have to interact with the C API. There is no alternative to scanf. I've build a little example:

main.swift

import Foundation

var output: CInt = 0
getInput(&output)

println(output)


UserInput.c

#include <stdio.h>

void getInput(int *output) {
    scanf("%i", output);
}


cliinput-Bridging-Header.h

void getInput(int *output);

Solution 4

In general readLine() function is used for scanning input from console. But it will not work in normal iOS project until or unless you add "command-line tool".

The best way for testing, you can do :

1. Create an macOS file

enter image description here

2. Use the readLine() func to scan optional String from console

 import Foundation

 print("Please enter some input\n")

 if let response = readLine() {
    print("output :",response)
 } else {
    print("Nothing")
 }

Output :

Please enter some input

Hello, World
output : Hello, World
Program ended with exit code: 0

enter image description here

Solution 5

edit As of Swift 2.2 the standard library includes readLine. I'll also note Swift switched to markdown doc comments. Leaving my original answer for historical context.

Just for completeness, here is a Swift implementation of readln I've been using. It has an optional parameter to indicate the maximum number of bytes you want to read (which may or may not be the length of the String).

This also demonstrates the proper use of swiftdoc comments - Swift will generate a <project>.swiftdoc file and Xcode will use it.

///reads a line from standard input
///
///:param: max specifies the number of bytes to read
///
///:returns: the string, or nil if an error was encountered trying to read Stdin
public func readln(max:Int = 8192) -> String? {
    assert(max > 0, "max must be between 1 and Int.max")

    var buf:Array<CChar> = []
    var c = getchar()
    while c != EOF && c != 10 && buf.count < max {
        buf.append(CChar(c))
        c = getchar()
    }

    //always null terminate
    buf.append(CChar(0))

    return buf.withUnsafeBufferPointer { String.fromCString($0.baseAddress) }
}
Share:
118,664
Chalkers
Author by

Chalkers

Updated on January 16, 2021

Comments

  • Chalkers
    Chalkers over 3 years

    I am attempting to get the keyboard input for a command line app for the new Apple programming language Swift.

    I've scanned the docs to no avail.

    import Foundation
    
    println("What is your name?")
    ???
    

    Any ideas?