Swift instance variable with protocol

I need 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 applies to an instance variable of type NSString . I found the link associated with the message , but I did not succeed. Using my MYModel.swift implementation of Xcode complains Cannot specialize non-generic type NSString

thanks 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 ... 
+5
source share
2 answers

< and > do not match the protocol. This applies to types with types such as an array:

 Array<T> 

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

You want something else, the variable must be of type String and conform to the protocol


You can extend String using the protocol and add the necessary functions yourself.

Since your Optional protocol is empty, just write:

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

To create a write protocol in Swift:

 protocol Optional {} 

You can also create an Objective-C protocol.


You should not use the option because it is already gone, but since Swift has a namespace, it works. You could, of course, write something like this:

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

Documentation link .

+1
source

The optional type declared in the Swift standard library is currently JSONModel incompatible with Swift because of this.

0
source

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


All Articles