xcode 条件绑定中的绑定值在 Swift 中必须是 Optional 类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27556911/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 06:23:13  来源:igfitidea点击:

Bound value in a conditional binding must be of Optional type in Swift

xcodemacosswiftinput

提问by user3708761

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

我正在尝试获取以下代码以允许我在控制台中输入 Accept 或 Reject;但是在线“如果 var userData = fileHandle.availableData{” 我收到错误

Bound value in a conditional binding must be of Optional type

条件绑定中的绑定值必须是 Optional 类型

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()

回答by i40west

The error is telling you that userDatahas to be of an optional type. But fileHandle.availableDatareturns an NSDatathat is not of an optional type. So you have to make it optional.

错误告诉您userData必须是可选类型。但fileHandle.availableData返回一个NSData不是可选类型的。所以你必须让它成为可选的。

(Also, your function is declaring that it returns a String, but you're not returning anything from it. And you can use letinstead of var. And userStringwill be an optional.) So:

(此外,您的函数声明它返回 a String,但您没有从中返回任何内容。您可以使用let代替var。AnduserString将是可选的。)所以:

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.availableDataactually 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:

但是,fileHandle.availableData实际上并不是失败的,这就是您首先收到错误的原因。该if var(或if let)构建想要一个可选的和函数不返回一个。因此,整个 if 测试是多余的,因为它不会失败。因此:

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 userStringline) is left as an exercise for the reader.

当然,这将接受任何输入,包括空字符串。验证用户数据(在该let userString行之后)留给读者作为练习。