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
Bound value in a conditional binding must be of Optional type in Swift
提问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 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.
错误告诉您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 let
instead of var
. And userString
will 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.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:
但是,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 userString
line) is left as an exercise for the reader.
当然,这将接受任何输入,包括空字符串。验证用户数据(在该let userString
行之后)留给读者作为练习。