I'm Dutch, so my English isn't very good. Sorry for that.
This is the answer that works:
import Foundation
print("What is your age?")
var fhcpy: NSData? = NSFileHandle.fileHandleWithStandardInput().availableData
if let data = fhcpy{
var str: String = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
var numstr: String = ""
for char in str.characters {
if Int("\(char)") != nil {
numstr.append(char)
}
}
var num: Int? = Int(numstr)
if let opNum = num {
print("Your age is \(opNum)")
} else {
print("That is not a valid number. ")
}
}
How I have done it
First, I tred the Swift 1.0 method, but that did cause a error (Get input in swift 1.0). It was the if let
method (Error handling). after that, I have made a optional called fhcpy
with the NSDate
value of fh.availbleData
. Which solved the problem of the if let
. Now we want to get an Int
value (Get Int value). Now we do that with Int(), but it returns every time nil
. We use a for to look what is inside the variable str
.
Code:
import Foundation
print("What is your age?")
var fhcpy: NSData? = NSFileHandle.fileHandleWithStandardInput().availableData
if let data = fhcpy{
var str: String = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
for char in str.characters {
print(char)
}
var num: Int? = Int(str)
print("Your age is \(num)")
}
Output:
What is your age?
12
1
2
Your age is nil
Program ended with exit code: 0
Did you see the newline? So we program a for
that tests for "If a character in the string is an Int
the Character
will be append to the strnum
". At the end, the strnum
is exported to an Int
.
Sample code:
import Foundation
print("What is your name?")
var fhcpy: NSData? = NSFileHandle.fileHandleWithStandardInput().availableData
if let data = fhcpy{
var str: String = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
print("Your name is \(str)")
}