The error is telling you that userData
has to be of an optional type. But fileHandle.availableData
returns an NSData
that is not of an optional type. So you have to make it optional.
(Also, your function is declaring that it returns a String
, but you’re not returning anything from it. And you can use let
instead of var
. And userString
will be an optional.) So:
func input() {
var fileHandle = NSFileHandle.fileHandleWithStandardInput()
println("Accept or Reject")
if let userData = fileHandle.availableData as NSData? {
let userString = NSString(data: userData, encoding: NSUTF8StringEncoding)
println("You have been \(userString!)")
}
}
input()
However, fileHandle.availableData
actually isn’t failable, which is why you’re getting the error in the first place. The if var
(or if let
) construct wants an optional and the function doesn’t return one. So, the entire if test is redundant as it can’t fail. Thus:
func input() {
var fileHandle = NSFileHandle.fileHandleWithStandardInput()
println("Accept or Reject")
let userData = fileHandle.availableData
let userString = NSString(data: userData, encoding: NSUTF8StringEncoding)
println("You have been \(userString!)")
}
input()
This will, of course, accept any input, including an empty string. Validating the user data (after the let userString
line) is left as an exercise for the reader.