Swift:测试nil的选项 [英] Swift: Testing optionals for nil
问题描述
我正在使用Xcode 6 Beta 4.我有这种奇怪的情况,我无法弄清楚如何正确测试选项。
I'm using Xcode 6 Beta 4. I have this weird situation where I cannot figure out how to appropriately test for optionals.
如果我有一个可选的xyz ,是正确的测试方法:
If I have an optional xyz, is the correct way to test:
if (xyz) // Do something
或
if (xyz != nil) // Do something
文件说是第一种方式,但我发现有时,第二种方式是必需的,并且不会产生编译器错误,但有时,第二种方式会产生编译器错误。
The documents say to do it the first way, but I've found that sometimes, the second way is required, and doesn't generate a compiler error, but other times, the second way generates a compiler error.
我的具体示例是使用GData XML解析器桥接到swift:
My specific example is using the GData XML parser bridged to swift:
let xml = GDataXMLDocument(
XMLString: responseBody,
options: 0,
error: &xmlError);
if (xmlError != nil)
在这里,如果我刚刚做了:
Here, if I just did:
if xmlError
它总是会返回true。但是,如果我这样做:
it would always return true. However, if I do:
if (xmlError != nil)
然后它可以工作(就像它在Objective-C中的工作原理一样)。
then it works (as how it works in Objective-C).
有什么东西有GData XML及其对待我缺少的选项的方式?
Is there something with the GData XML and the way it treats optionals that I am missing?
推荐答案
在xcode beta 5中,他们不再允许你这样做
In xcode beta 5, they no longer let you do
var xyz : NSString?
if xyz {
//Do Something
}
产生错误不符合协议'BooleanType.Protocol'
你必须要做其中一个陈述:
You have to do one of these statements:
if xyz != nil {
//Do Something
}
if let xy = xyz {
//Do Something
}
这篇关于Swift:测试nil的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!