2

I'm trying to get the code below to allow me to input Accept or Reject into the console; however on line "if var userData = fileHandle.availableData{" I get the error

Bound value in a conditional binding must be of Optional type

func input() -> String {
   var fileHandle = NSFileHandle.fileHandleWithStandardInput()
   println("Accept or Reject")
   if var userData = fileHandle.availableData{
       var userString = NSString(data: userData, encoding: NSUTF8StringEncoding)
       println("You have been \(userString)")
   }
}

input()
jww
  • 97,681
  • 90
  • 411
  • 885
user3708761
  • 275
  • 1
  • 6
  • 14
  • 1
    The answer in that thread is too vague to help me with this problem. – user3708761 Dec 18 '14 at 22:48
  • That other one is more about optionals as pertains to conditional casting; this question can stand on its own. (Unless there's another question about APIs that return non-optional values and an answer like @i40west's.) – rickster Dec 19 '14 at 06:22

1 Answers1

7

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.

Jeremy
  • 4,339
  • 2
  • 18
  • 12