Xcode Swift: string input in swift

Опубликовано: 30 Март 2026
на канале: solron75
10,964
18

Xcode Swift: string input in swift

A new updated video here:    • Swift String Input in OS X (updated)  

Please go to http://soltveit.org/xcode-swift-strin...
for a correct listening as YouTube doesnt allow all characters.

When I first started with Swift, I didn't think that a Swift String Input would be a issue. But it seems like at the moment there is no methods of getting a string input from terminal or console. You will have to use some Objective C statements to achieve this. They are easily accessible so there is no problem in getting them. You can paste this code and create your own Input method. Here is the Swift String input code:

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

The way you want to use this, is about the same way as with some sort of C language.

print("Enter: ")
var string1 = input()
println("You typed: " + string1)

You can also do it in a "one liner" if you only need to do it once. If you need to do this more than once, I would just go with the first method. Because the printing of the result is also a bit more to it now, as you need to convert it from a NSString to a string.


println("Enter 2: ")
var string2 = NSString(data: NSFileHandle.fileHandleWithStandardInput().availableData, encoding: NSUTF8StringEncoding)
println("You Typed: " + (NSString(string: string2!) as! String))

And that was the second method.

This is one way to get a swift string input. Beware if you just press enter, and pass in an empty string. There might be some trouble in your code.