4

I'm combining Swift and Objective-C in the same project. I am trying to use STTwitter cocoapod like this:

// objective-c
// STTwitter category method
//
- (void)getStatusesLookupTweetIDs:(NSArray *)tweetIDs 
                     successBlock:(void (^)(NSArray *))successBlock 
                       errorBlock:(void (^)(NSError *))errorBlock {

    [self getStatusesLookupTweetIDs:tweetIDs
                    includeEntities:@(YES)
                           trimUser:@(YES)
                                map:@(YES)
                       successBlock:successBlock
                         errorBlock:errorBlock];
}

Swift Code

// swift
twitterApi.getStatusesLookupTweetIDs(ids, successBlock: { (tweets: [AnyObject]!) -> Void in
    process(tweets)
    finish()
}, errorBlock: { (err) -> Void in
    error(err)
})

Everything looks fine in Obj-C (I tried not investigate variable passed to successBlock, they all have valid values). But in Swift, when successBlock gets executed, tweets was:

Printing description of tweets:
([AnyObject]!) tweets = 1 value {
  [0] = <error: use of undeclared identifier 'cocoarr'
error: 1 errors parsing expression
>

}

How do I fix this and pass NSArray into Swift? (No compile error)

Daiwei
  • 40,666
  • 3
  • 38
  • 48

2 Answers2

0

That worked for me.

Instead of using:
[AnyObject]
try to use:
[Dictionary<String, AnyObject>] (or whatever class is inside the array)

Try to specify the type of the array instead AnyObject.

I hope it helps.

Cheers.

  • Sorry the project has been long deleted. So no way to re-create. Could someone else confirm this for me? – Daiwei Jan 14 '15 at 21:22
  • Get this warning `cannot specialize non-generic type nsdictionary` when trying that code – Sunkas Apr 02 '15 at 09:16
0

Try [[String:AnyObject]] rather than [AnyObject]

I got the same error in a smilar functionality. When changing from:

if let dictOrList = NSJSONSerialization.JSONObjectWithData(data, options:nil, error: &err) as? NSDictionary {
    callbackList = [dictOrList]
} else if let list = NSJSONSerialization.JSONObjectWithData(data, options:nil, error: &err) as? [AnyObject] {
    callbackList = list
}

to

if let dictOrList = NSJSONSerialization.JSONObjectWithData(data, options:nil, error: &err) as? [String: AnyObject] {
    callbackList = [dictOrList]
} else if let list = NSJSONSerialization.JSONObjectWithData(data, options:nil, error: &err) as? [[String:AnyObject]] {
    callbackList = list
}

I got it working.

Sunkas
  • 9,542
  • 6
  • 62
  • 102