I have a Objective-C application working fine and smooth, to be more comfortable with Swift I decided to write the unit tests for this app in Swift.
Some concepts in Swift looks weird for me, for example, in my app need to fill up a list of contents provided by server, in Objective-C, this looks (not exactly) like this:
[self.service requestContentsFrom:0 to:10 response:^(NSArray *result, NSArray *errors) {
ContentModel *firstContent = result[0];
NSLog("Content name: %@ Content date: %@", firstContent.name, firstContent.date);
}];
I this simple request, if result list (NSArray) be filled, I'll receive a list of ContentModel, because service instance implements some serialization level (thanks to JSONModel)
To make a simple test for this request in Swift, I did something like this:
func testContentsFromZeroToTen() {
service?.requestContentsFrom(0, 10) { (result, errors) -> Void in
}
}
The point of my question is, in Swift my result argument comes to [AnyObject]! and looks like this array are filled correctly, but the type inside that is not the same I received by Objective-C call.
If I try to cast to NSArray, for example....
let contents = result as NSArray
... then each content printed in console, looks like this:
(AnyObject) content = (instance_type = Builtin.RawPointer = 0x00007fd605213000 -> 0x000000010fa902c8 (void *)0x000000010fa902f0: __NSCFDictionary)
The most curious is, if I print contents, I can see more consistent information about it:
<__NSCFArray 0x7f95d7608110>(
{
datetime = 1418855742226;
id = 1;
name = "Content 1";
},
{
datetime = 1418855742326;
id = 2;
name = "Content 2";
)
Hey! my model is there, but where is my typed model, instead of a ContentModel, I see __NSCFDictionary
I hope to get an Swift array like this:
let contents = result as [ContentModel]
But when I try the code above, my contents looks like this when I print in console:
([ContentModel]) contents = 2 values {
[0] = <error: use of undeclared identifier 'cocoarr'
error: 1 errors parsing expression
>
[1] = <error: use of undeclared identifier 'cocoarr'
error: 1 errors parsing expression
>
}
So the question is, how can I cast Swift array correctly to get my typed NSArray like Objective-C?
UPDATE 1: Added ContentModel interface
#import <Foundation/Foundation.h>
#import "JSONModel.h"
#import "UserModel.h"
@interface ContentModel : JSONModel
@property (nonatomic, assign) NSInteger id;
@property (nonatomic, strong) NSDate *datetime;
@property (nonatomic, strong) NSString *text;
@property (nonatomic, strong) UserModel *user;
@end
contents[0]and try to use it as a ContentModel. Can you? If so, no problem.cocoarr? That looks like a clue.ContentModeleven implicitly.