8

I am new to Apple programming and I thought I'd try out Swift, but I have no idea how to get user input and store it in a variable. I am looking for the simplest way to do this, something like input() and raw_input() in Python.

# Something like this (Python code)
name = raw_input() # name is a string
print "Your name is ", name
number = input() # number is an int or float
Matthias Bauch
  • 89,811
  • 20
  • 225
  • 247
Jeremy M
  • 121
  • 1
  • 2
  • 6

1 Answers1

13

This is actually not easy in Swift at this point. The simplest way is probably the Objective-C way, using an NSFileHandle with standard input:

import Foundation

var fh = NSFileHandle.fileHandleWithStandardInput()

println("What is your name?")
if let data = fh.availableData {
    var str = NSString(data: data, encoding: NSUTF8StringEncoding)
    println("Your name is \(str)")
}

Or for continuous input:

println("I will repeat strings back at you:")
waitingOnInput: while true {
    if let data = fh.availableData {
        var str = NSString(data: data, encoding: NSUTF8StringEncoding)
        println(str)
    }
}

The possible encodings are shown here.

Joseph Mark
  • 9,298
  • 4
  • 29
  • 31