Friday, 15 March 2013

How to annotate Objective-C APIs for use in Swift (e.g. return types) -



How to annotate Objective-C APIs for use in Swift (e.g. return types) -

according xcode release notes, apple has been "auditing" existing apis remove implicitly unwrapped optionals. means instead of t!, apis homecoming t or t? appropriate.

where this? how can annotate/wrap existing objective-c code (especially libraries) create cleaner utilize swift?

xcode 6.3/swift 1.2

xcode 6.3 added official back upwards annotating nullability in objective-c.

nullability

the nullability of value can declared annotating type keywords __nullable, __nonnull , __null_unspecified (the default). in properties , methods keywords nullable, nonnull , null_unspecified.

examples xcode release notes

- (void)registernib:(nonnull uinib *)nib forcellreuseidentifier:(nonnull nsstring *)identifier; - (nullable uitableviewcell *)cellforrowatindexpath:(nonnull nsindexpath)indexpath; @property (nonatomic, readwrite, retain, nullable) uiview *backgroundview; changing default

null_unspecified (which translates t!) default existing code. useful feature ability alter default sections of api.

ns_assume_nonnull_begin // nonnull default here ns_assume_nonnull_end

this removes lot of noise, since methods take , handle nil exception, not rule. personally, utilize audited apis.

null_resettable

null_resettable additional annotation used uncommon case can set property nil, never be nil (because resets default value).

@property (nonatomic, retain, null_resettable) uicolor *tintcolor;

personally, avoid behavior new code. hybrid nature of such properties isn't fit swift.

xcode 7/swift 2 (beta)

xcode 7 adds back upwards annotating generic types in objective-c.

generic type annotations collections

nsarray, nsset , nsdictionary (which automatically bridged swift's array, set , dictionary can annotated type of contents.

@property nsarray<nsstring *> *stringarray; @property nsset<nsstring *> *stringset; @property nsdictionary<nsstring *, nsstring *> *stringdict;

there's __kindof keyword tells objective-c compiler less strict , allow downcasting. doesn't impact swift side.

generic type annotations custom classes @interface myarray1<__covariant t> : nsobject - (void)addobject:(t)object; @end @interface myarray2<__covariant t : nsobject *> : nsobject - (void)addobject:(t)object; @end @interface myarray3<__covariant t : id<nscopying>> : nsobject - (void)addobject:(t)object; @end

the @implementation doesn't know t , uses id/nsobject */id<nscopying> did.

objective-c swift

No comments:

Post a Comment