The type that NSFileHandle gives you for num1
and num2
is NSData.
You can't do math on NSData, you have to first convert the data to numbers.
To transform this data into integers, we're doing two steps: first convert the data to an NSString, then convert the string to an Integer. After that, we can sum the two values.
We're using the integerValue
method of NSString
:
let fh = NSFileHandle.fileHandleWithStandardInput()
print("Please input first number")
let num1 = fh.availableData
print("Please input second number")
let num2 = fh.availableData
if let numString1 = NSString(data: num1, encoding: NSUTF8StringEncoding),
numString2 = NSString(data: num2, encoding: NSUTF8StringEncoding) {
let val1 = numString1.integerValue
let val2 = numString2.integerValue
print("\(val1) + \(val2) = \(val1 + val2)")
}
Result:
Please input first number
33
Please input second number
42
33 + 42 = 75