Using Restkit with Swift

I am trying to use RestKit in my Swift based project. It seems like I can't use Swift primitive data types such as Int, Double, Bool, etc., Except for String, Array and Dictionaries (which seems to be due to the fact that they are duty-free connected to NSString. NSArray and NSDictionary)

With objective-c, I could define properties in my objects as primitive data types as properties that are assigned. In Swift, I can only use objects (String, NSNumber, Array, Dictionary), otherwise the application will fail using "setValue: forUndefinedKey: this class is not suitable for encoding the key for the aBool key".

Example: Here is how my object will look in Objective-C:

@interface TestObject : NSObject @property (strong, nonatomic) NSString *aString; @property (assign, nonatomic) BOOL aBool; @property (assign, nonatomic) CGFloat aFloat; @end 

and the "equivalent" in Swift:

 class TestObject:NSObject { var aString:NSString? var aBool:Bool? var aFloat:Double? } 

What happens, and when I understand WHY it crashes, I would like to know if there is another workaround than using NSNumber for Booleans, Integer and Floats, just like it works in Objective-C?

(If any of the RestKit developers reads this: First of all, thanks for your work, and then: Are there any plans for Swift support / port for Swift?)

+5
source share
2 answers

I am making an application in Swift, and we started work in the summer of 2014 when Swift was completely new. I started using RestKit to handle REST communication with the server, and I spent at least a full month setting up RestKit for my use.

Until I know your use case, it was easier for me to use Alamofire and SwiftyJSON to work. It saved me many hours. It also means that I manually do the conversion from dynamic types to object types, but the time spent on it is much less than the time I previously spent setting up RestKit.

If this is not a viable way for you, you might want to take a look at the RKValueTransformer classes available in RestKit; in your RKObjectMapping you can specify your own transformers for individual properties. But then again, I think the time is better spent on Alamofire and SwiftyJSON. After all, these are native Swift libraries.

+8
source

For those who cannot refuse RestKit in the Swift project, this solution can be useful.

In my case, the application crashes because RestKit was not able to match the "true" / "false" strings from JSON to type Bool in Swift.

I decided to add another String attribute to my class and update the required boolean using the didSet method. In your case, it will be:

 class TestObject:NSObject { var aString:NSString? var aBool:Bool? var aFloat:Double? var aBoolString: String? { didSet { self.aBool = aBoolString.lowercased() == "true" } } } 

Hope this helps!

0
source

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


All Articles