2

I was implementing UITableView in Swift and comparing it to Objective-C counterpart.

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

From Swift I'm returning an unwrapped optional. If i know I'm returning a non nil optional then why is the return type an optional at all? I'm also passing in uitableview as an unwrapped optional. The same wisdom applies.

It makes sense if I'm returning an optional and using a question mark to say i don't know if I'm returning a value or nil.. But I don't understand this specific case

jscs
  • 63,694
  • 13
  • 151
  • 195
hamobi
  • 7,940
  • 4
  • 35
  • 64

2 Answers2

4

It's just a matter of interfacing with the Objective-C APIs. Any object reference might be nil, and Swift needs to express that fact, so an Optional is needed. But by using an implicitly unwrapped Optional, Swift frees you from any concern over the fact that it's an Optional at all; you can just treat it as thing wrapped by the Optional, and let Swift worry about crossing the bridge for you.

Let's take the separate cases separately:

The Returned Value

You might pass nil here, because any object reference could be nil. So the return value is typed as an unwrapped optional. In reality, you just pass the table view cell object.

The Incoming Table View

It might be nil, because any object reference could be nil, but in fact you know it won't be. It is unwrapped implicitly for you, so in reality you can just use it as a table view.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • and you can use closures as default values for optional parameters. http://stackoverflow.com/a/27513392/2237853 – izzy Dec 20 '14 at 23:27
1

Imagine you're not implementing this method but instead calling it on a class that was defined in Objective-C. The Objective-C class could return nil so the protocol definition has to reflect that. Even though in Swift you could guarantee that your method will never return nil, you can't have a different return type while still conforming to the protocol.

If you're writing your own protocol just in the context of Swift, then you can definitely drop the optional for added safety.

Brian Nickel
  • 26,890
  • 5
  • 80
  • 110