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?
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?
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
UserInput.c
cliinput-Bridging-Header.h
The top ranked answer to this question suggests using the readLine() method to take in user input from the command line. However, I want to note that you need to use the ! operator when calling this method to return a string instead of an optional:
I managed to figure it out without dropping down in to C:
My solution is as follows:
More recent versions of Xcode need an explicit typecast (works in Xcode 6.4):
Before
*******************.
Correction
This works in xCode v6.2, I think that's Swift v1.2
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.