I have a simple TwitterTweet struct:
struct TwitterTweet {
let userName: String
let userDescription: String
let userFollowersCount: Int
let userProfileImage: String
let tweetText: String
let tweetRetweetCount: Int
let tweetFavouriteCount: Int
}
and an array of the TwitterTweet struct:
//var twitterTweets: [TwitterTweet]?
var twitterTweets = [TwitterTweet]()
I retrieve and parse JSON data into an array of NSDictionary. In the for-loop, I create a new TwitterTweet, but when I try and add it to the array at index i, i get the error:
fatal error: Array index out of range
if let data = NSJSONSerialization.JSONObjectWithData(responseData, options: nil, error: &err) as? [NSDictionary] {
if data.count != 0 {
for var i = 0; i < data.count; i++ {
if let
tt = data[i]["text"] as? String,
rc = data[i]["retweet_count"] as? Int,
tc = data[i]["favorite_count"] as? Int {
if let ud = data[i]["user"] as? NSDictionary {
if let
un = ud["name"] as? String,
dc = ud["description"] as? String,
fc = ud["followers_count"] as? Int,
pi = ud["profile_image_url"] as? String {
let tweet = TwitterTweet(userName: un, userDescription: dc, userFollowersCount: fc, userProfileImage: pi, tweetText: tt, tweetRetweetCount: rc, tweetFavoriteCount: tc
self.twitterTweets[i] = tweet
}
}
}
}
}
else {
println("no data")
println("error: \(error)")
}
I am not sure how to assign the array with size of data.count. I have tried adding the following code before the for-loop
twitterTweets = [TwitterTweet](count: data.count, repeatedValue: nil)
But this does not work for me. Any help or suggestions are greatly appreciated, as I have already spent hours trying to figure out a solution. Thanks.