Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift instance variable with protocol

I have to translate the following lines of Objective-c code into swift. This is a sample from the Objective-c JSONModel-Framework where the Optional protocol provided by the Framework is applied to an instance variable of type NSString. I found a related post but i didn't managed to achieve it. With my MYModel.swift implementation Xcode complains Cannot specialize non-generic type NSString

thx for your help!

MYModel.swift

@objc(MYModel) public class MYModel : JSONModel {
   ...
   public var name : NSString<Optional>
   ...
}

MYModel.h

@interface MYModel : JSONModel
...
@property (strong, nonatomic) NSString<Optional>* name; 
...

JSONModel.h

...
/**
 * Protocol for defining optional properties in a JSON Model class. Use like below to define 
 * model properties that are not required to have values in the JSON input:
 * 
 * @property (strong, nonatomic) NSString<Optional>* propertyName;
 *
 */
@protocol Optional
@end
...
like image 413
robbiebubble Avatar asked Nov 10 '22 02:11

robbiebubble


1 Answers

The < and > are not for conforms to protocol. It is for Types with generics like Array:

Array<T>

so you can write var a: Array<String>.

You want something else, a variable should be a Type String and conform to the protocol


You can extend String with the protocol and add the needed functions yourself.

Since your Optional protocol is empty, it is enough to write:

extension NSString: Optional {} // you can use String if you like

To create the protocol write in Swift:

protocol Optional {}

You can Objective-C create the protocol, too.


You should not use Optional, because there is already one, but because Swift has namespacing, it works. You could of course write something like that:

extension NSString: JsonOptProtocol {}

protocol JsonOptProtocol {} // or create that in Objective-C like you did

Documentation link.

like image 122
Binarian Avatar answered Nov 14 '22 23:11

Binarian