Swift: How to input a number from CLI Command Line Interface

Is there no input() function in Swift? No. Not for now. But how then can we enter a number or a string from the command line interface (CLI)?

1. Copy this function to your code:

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

2. Use it like so:

print("Enter number: ")
let n_str = input()       // NOTE: n_str is an Optional (type), this means String or nothing
let n = n_str.toInt()!    // NOTE: ! "unpacks" the Optional type n_str

 

3. Testing: What happens, if I enter a Number:

Enter number: 12

Result: Just seems to work

 

4. Testing: What happens if I just enter ENTER:

Enter number:        // <--- I just hit ENTER here
fatal error: unexpectedly found nil while unwrapping an Optional value
0  swift                    0x00000001039d82b8 llvm::sys::PrintStackTrace(__sFILE*) + 40
1  swift                    0x00000001039d8794 SignalHandler(int) + 452
[...]

Result: It crashes, which is better then continue with undefined values

5. Testing: What happens if I just enter a string not a number:

Enter Number: abc
fatal error: unexpectedly found nil while unwrapping an Optional value
0  swift                    0x000000010bc512b8 llvm::sys::PrintStackTrace(__sFILE*) + 40
1  swift                    0x000000010bc51794 SignalHandler(int) + 452
[...]

Result: It does crash, witch is better then continue with undefined values!

6. Conclusion

So, sometimes it's a better your program crashes then just go ahead somehow undefined as it's possible with plain C for example.

Missing Swift Computer Language Feature: But really, Swift should and has to include an input() function by default. Apple, if you read this, just do it 😉 Swift seems to be a great new computer language and I start to really like it.

 

Helpful?

Swift: How to input a number from CLI Command Line Interface

Leave a Reply

Your email address will not be published. Required fields are marked *