Thursday, February 3, 2022

Optionals in Swift Objective-C Interoperability

Fabián Cañas (via Zev Eisenberg):

The scroll view property, which should be nonnull, or in Swift, not optional, is never given a value on initialization. So what happens when we use if from Swift?


Any Objective-C things we want to do with these objects succeeds, which is nearly everything since they’re Objective-C objects. We’ve entered the territory of undefined behavior. It’s a sort of “Objective-C mode”.

There are things we can do to detect this non-optional nil condition. […] The problem is that since Swift doesn’t think this value can be nil, it’s not trivial to check.


If you make a Swift extension to the Objective-C class and call them on one of these nil things that aren’t supposed to exist, those methods still get called.

I guess this is because methods defined in Swift are by default not dynamic.

Nonnull array properties in Objective-C get bridged to Swift in a very strange way. […] This situation doesn’t look self-consistent. Under some conditions, Swift will create an Array if it doesn’t find one where it’s expected.


1 Comment RSS · Twitter

At this point when I’m working with an Obj-c class I tread all the values as nil and do my best to guard and unwrap them

Leave a Comment