When you make an implicitly unwrapped optional in Swift, it does not mean that it is always going to be non-nil: all it means is that you tell the compiler that when you access their properties, you expect the object to be non-nil
. The object that you reference can be explicitly checked for nil
; setting it to nil
will not cause an exception either, unless you try to access any of its properties after that.
When Apple used implicitly unwrapped optionals for the parameters of
func tableView(_ tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
function, they let you save on a few extra if
- let
. In this case, they know that they never pass you a nil
; in other cases, they do not know it, and they expect you to nil
-check the object.
They allow you to return nil
, too. It is up to them to check the results for nil
, unless, of course, you decide to call that function yourself. Although I cannot think of a valid reason to call cellForRowAtIndexPath
from your own code, if you do make a call, it would be your responsibility to check the return value for nil
.
If you consider an alternative of making the parameters UITableView?
and NSIndexPath?
instead, all implementations would have to either use an exclamation point after tableView
and indexPath
, or use the if
- let
idiom. Compared to this choice, implicitly unwrapped types look like a better choice.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…