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
...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With