Input from the keyboard in command line applicatio

2019-01-04 07:00发布

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?

16条回答
可以哭但决不认输i
2楼-- · 2019-01-04 07:31

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

查看更多
神经病院院长
3楼-- · 2019-01-04 07:31

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.

print("What is your full name?")

var arr = readLine()!.characters.split(" ").map(String.init)

var firstName = ""
var middleName = ""
var lastName = ""

if arr.count > 0 {
    firstName = arr[0]
}
if arr.count > 2 {
    middleName = arr[1]
    lastName = arr[2]
} else if arr.count > 1 {
    lastName = arr[1]
}

print("First Name: \(firstName)")
print("Middle Name: \(middleName)")
print("Last Name: \(lastName)")
查看更多
Lonely孤独者°
4楼-- · 2019-01-04 07:32

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.

查看更多
混吃等死
5楼-- · 2019-01-04 07:32

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?

[NSString.alloc initWithData:
[NSFileHandle.fileHandleWithStandardInput availableData]
                          encoding:NSUTF8StringEncoding];

if you want it WITHOUT the trailing newline, just add...

[ ... stringByTrimmingCharactersInSet:
                       NSCharacterSet.newlineCharacterSet];

Ta Da! ♥ ⱥᏪℯⅩ

查看更多
混吃等死
6楼-- · 2019-01-04 07:33

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:

var i: CInt = GetInt()
println("Your input is \(i) ");

Bridging Header:

#include "obj.m"

int GetInt();

obj.m:

#import <Foundation/Foundation.h>
#import <stdio.h>
#import <stdlib.h>

int GetInt()
{
    int i;
    scanf("%i", &i);
    return i;
}

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

查看更多
我命由我不由天
7楼-- · 2019-01-04 07:38

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.

    let inputStr = readLine()
    if let inputStr = inputStr {
        print(inputStr)
    }
查看更多
登录 后发表回答