Objective-C will be gradually replaced with Swift. Before that, there is a lot of opportunity to boost your Objective-C code embracing Swift. This article is the keynote of WWDC Refine Objective-C frameworks for Swift.

Summary

1. Provide richer type information
  1.1. Describe nullability to control optionals
  1.2. Nullability mistakes

2. Follow Objective-C conventions
  2.1. Use Objective-C generics for Foundation types
  2.2. Use Int for numbers
  2.3. Strengthen stringly-typed constants
  2.4. Specify initializer behavior
  2.5. Follow the error handling convention
3. Address missing APIs
  3.1. Fix missing APIs
4. Improve ergonomics in Swift
  4.1. Improve naming
  4.2. Improve error code enums

Provide richer type information

Describe nullability to control optionals

The picture below depicts the default generated behavior without nullability annotation.

By adding the nullability to make our code more robust.

Constant, Global function, Block using underscore qualifier, and it becomes optional or non-optional in Swift.

Nullability mistakes

The nonnull annotation was wrong when Objc returns nil for a value Swift thinks can’t be optional if you are using the NSString or NSArray on Objc side. You will end up with an invalid object and it’s hard to be noticed, because Objc method calls ignore nil, but in some cases, you’ll crash with a null pointer dereference or get other unexpected behavior.

The compiler doesn’t promise anything about what happens. So switching to Release mode or changing Xcode versions could change the symptoms of this kind of bug. Swift believes what Objc header that something can’t be nil, Swift doesn’t force-unwrap it, so you won’t see a crash at the place where it returned nil.

The Objc compiler and the clang static analyzer also check the nullability annotations.

Suppose you see some warnings or analyzer results, and can’t quite decide if they can actually happen.

null_unspecified, which makes Swift import the value as an implicitly unwrapped optional. If you not sure the API will return nil or not, use null_unspecified in case of some impossible seeming misbehavior sometime later.

#objective-c #wwdc-2020 #swift #c #programming-c

Refine Objective-C Frameworks for Swift
1.90 GEEK