Xcode: Swift String Input in command line

Swift String Input

Swift String Input

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:

Please see this for an updated version

 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.

Here is a link to the swift documentation from Apple

Same as above, but on video.

Thats it. Happy inputing!

About Author

Related Posts

Xcode 9 iOS icon sizes

Xcode 9 iOS icon sizes overview

Xcode 9 iOS icon sizes overview Xcode 9 iOS icon sizes overview. They keep adding more and more icon sizes. Xcode 9 has the most icon sizes…

Xcode 9 uiimage image not shown

Xcode 9 uiimage image not shown

Xcode 9 uiimage image not shown Working on some ios apps created with Xcode 8 and your images don’t show after upgrading to Xcode 9? Took me awhile…

Xcode 8 iOS icon sizes overview

Xcode 8 iOS icon sizes overview Xcode 8 iOS icon sizes overview. There are even more icon sizes since Xcode 7. And it can be an extra challenging…

Swift Capitalize

Swift Capitalize words, How to

Swift Capitalize, How to Swift Capitalize is done with a string instance property. Check the example below to see how to use it. There is also a link…

Swift Debian

Swift Debian 8 (Jessie)

Swift Debian 8 (Jessie) Swift, Apples new programming language, to take over for Objective C has been open source for some time now. It only took at…

didMove never get called

Xcode – didMove never get called

didMove never get called in Xcode? didMove never get called when creating a new project with Xcode using the Game template. I selected Swift and SpriteKit. I…

This Post Has One Comment

Leave a Reply