[英]Why sample iOS app in XCode 6 checks for nil of a non-optional variable?
In "Master-Details" sample Swift app that comes with XCode 6 in MasterViewController.swift
file they define objects
like this: 在“Master-Details”示例中,在
MasterViewController.swift
文件中随附XCode 6的Swift应用程序,它们定义了如下objects
:
var objects = NSMutableArray()
Then in insertNewObject
method they check against nil
before using it: 然后在
insertNewObject
方法中,他们在使用之前检查nil
:
func insertNewObject(sender: AnyObject) {
if objects == nil {
objects = NSMutableArray()
}
objects.insertObject(NSDate.date(), atIndex: 0)
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
If objects
is not optional and objects = nil
throws an error, why do they need to guard against nil
? 如果
objects
不是可选的并且objects = nil
会抛出错误,为什么他们需要防范nil
?
That is a bug; 那是一个错误; I find it surprising that it compiles without an error or warning.
我发现它编译没有错误或警告令人惊讶。 (I guess it's probably being turned into a call to isEqual:, passing nil?) Interestingly, the more idiomatic version:
(我猜它可能会变成对isEqual:的调用,传递nil?)有趣的是,更惯用的版本:
if objects {
objects = NSMutableArray()
}
Does actually fail; 实际上是失败了; you get an error on the
if objects
line because you can't test an NSMutableArray for boolean-ness. 你在
if objects
行上得到一个错误,因为你无法测试NSMutableArray的boolean-ness。
You don't need to guard against nil
. 你不需要防范
nil
。 That's the entire point of optionals (or non-optionals). 这是期权(或非期权)的全部观点。 Also, in Swift, when you are testing for
nil
, if the variable is an optional (which is the only time it could be nil
anyhow), you can just say: 此外,在斯威夫特,当您正在测试的
nil
,如果变量是一个可选的(这也可能是唯一一次nil
无论如何),你可以说:
if optionalVar {
// do stuff
}
This is probably just translated from the Objective-C version by Xcode and isn't made "Swifty." 这可能只是由Xcode从Objective-C版本翻译而来,并不是“Swifty”。
Another instance of this kind of thing: 这种事的另一个例子:
init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
// Custom initialization
}
The // Custom initialization
should go above the super.init()
in Swift, but this is just translated from the Objective-C version. // Custom initialization
应该高于Swift中的super.init()
,但这只是从Objective-C版本翻译而来。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.