Importing Objective-C properties explicitly in Swift as optional parameters

Update: Starting with Xcode 6.3, this is now possible through zeroing annotations .

I was wondering if anyone figured out a way to explicitly import Obj-C objects into Swift as optional.

Problem

Consider the following ObjC class:

@interface Foo : NSObject @property (strong, nonatomic) NSObject* potentiallyNil; @end 

That's great and all, but when you go to use it in Swift, Xcode tends to import the property as its own instance or as an implicitly unwrapped optional.

I saw how it happened as in

 class Foo : NSObject { var potentiallyNil : NSObject } 

and

 class Foo : NSObject { var potentiallyNil : NSObject! } 

Now here is the problem with this - in Swift, you got this ugly problem - to know that your property may be zero, but you need to avoid the beauty of an implicit additional transformation. You have one of the following options:

Explicit verification of nil ...

 if(potentiallyNil == nil) { bar() } 

Or manual conversion to an optional type with unpacking is also ugly ...

 let manuallyWrappedPotentiallyNil : NSObject? = potentiallyNil if let unwrapped = manuallyWrappedPotentiallyNil { bar(); } 

Both of them seem far from ideal. I think there MUST be a way around this! In fact, as @matt noted, Apple did this on its own in all beta versions, while it was “audited for additional compliance”. Can we do the same?

Question

This boils down to the following: given the ObjC property

 @property (strong, nonatomic) NSObject* potentiallyNil; 

is there any way to get this to import in signature swift

 var potentiallyNil : NSObject? 

Many thanks to all of you, other iOS / OS X developers.

+5
source share
2 answers

At the time of asking this question this was not possible. However, in Xcode 6.3 there is a new annotation function noability to enable this previously closed functionality. Therefore, the question no longer matters.

+1
source

If you check the API code, you will see that there are Swift and Objective-C classes. So, I guess Apple's solution for this problem?

0
source

Source: https://habr.com/ru/post/1202926/


All Articles