Why this pattern?

This is as much about programming in general as it is about swift.

From UIKit, we get this:

func touchesBegan(
    _ touches: Set<UITouch>,
    with event: UIEvent?

This function would be almost pointless without an event object. The docs don't suggest you would ever not get an event. So why is this an Optional?

It’s optional in Swift because it’s marked nullable in Objective-C. That annotation is presumably there for a reason, but that reason is out of scope for the Swift forums.


But also, I think the function is still useful even without an event, because you still have the set of touches; you can get their position as well as other useful info about them.

Yep, that's why I said almost. Maybe useless is a bit strong. This probably devolves to complaints about Apples, docs, which I'll skip.

Yeah, I was hoping there was some more general pattern being used which I didn't know about.

I don't think UIKit ever calls touchesBegan() with a nil event, but it's an API where you override a method and then manually forward the event on if you didn't handle it, and that forwarding may not properly forward the event. It unfortunately originally permitted forwarding nil, and it's difficult to change it to non-nullable after the fact.

If the same thing were being designed today in Swift I suspect the event parameter would not be optional.


In some older UIKit APIs, collections are made nullable and nil is used instead of an empty collection. One of the most prominent examples is UICollectionView’s indexPathsForSelectedItems property:

The value of this property is an array of NSIndexPath objects, each of which corresponds to a single selected item. If there are no selected items, the value of this property is nil.

I’m not sure if this is the case for touchesBegan, though.

1 Like