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?
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
2. Use the readLine() func to scan optional String from console
Output :
If you want to read space separated string, and immediately split the string into an array, you can do this:
var arr = readLine()!.characters.split(" ").map(String.init)
eg.
The correct way to do this is to use
readLine
, from the Swift Standard Library.Example:
Will give you an Optional value containing the entered text.
I swear to God.. the solution to this utterly basic problem eluded me for YEARS. It's SO simple.. but there is so much vague / bad information out there; hopefully I can save someone from some of the bottomless rabbit holes that I ended up in...
So then, lets's get a "string" from "the user" via "the console", via
stdin
, shall we?if you want it WITHOUT the trailing newline, just add...
Ta Da!
♥ ⱥᏪℯⅩI have now been able to get Keyboard input in Swift by using the following:
In my main.swift file I declared a variable i and assigned to it the function GetInt() which I defined in Objective C. Through a so called Bridging Header where I declared the function prototype for GetInt I could link to main.swift. Here are the files:
main.swift:
Bridging Header:
obj.m:
In obj.m it is possible to include the c standard output and input, stdio.h, as well as the c standard library stdlib.h which enables you to program in C in Objective-C, which means there is no need for including a real swift file like user.c or something like that.
Hope I could help,
Edit: It is not possible to get String input through C because here I am using the CInt -> the integer type of C and not of Swift. There is no equivalent Swift type for the C char*. Therefore String is not convertible to string. But there are fairly enough solutions around here to get String input.
Raul
When readLine() function is run on Xcode, the debug console waits for input. The rest of the code will be resumed after input is done.