0

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.

1 Answer 1

2
twitterTweets += [tweet]

or

twitterTweets.append(tweet)

or

twitterTweets.splice([tweet], atIndex: i)
Sign up to request clarification or add additional context in comments.

1 Comment

No problem! Sometimes just writing out the question helps… sometimes you have to wait for someone to answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.