1

I've created a multidimensinal array which is suppose to hold different sections of news for instance popular and Recent news. i've therefore created a array like this where News is my class.

 var arrayNews = Array<Array<News>>()

After this i'm looping through my first JSON file like this

    for (key: String, subJson: JSON) in jsonArray {
        // Create an object and parse your JSON one by one to append it to your array
        var newNewsObject = News(id: subJson["id"].intValue, title: subJson["title"].stringValue, link: subJson["url"].stringValue, imageLink: subJson["image_url"].stringValue, summary: subJson["news_text"].stringValue, date: subJson["date"].stringValue)


        arrayNews.append(newNewsObject)
    }

However i'm getting following error when i try to append it to the array?

cannot invoke append with an argument list of type (News)

Testing answer

var arrayNews = Array<Array<News>>()
let recentArray = [News]()

    for (key: String, subJson: JSON) in jsonArray {
        // Create an object and parse your JSON one by one to append it to your array
        var newNewsObject = News(id: subJson["id"].intValue, title: subJson["title"].stringValue, link: subJson["url"].stringValue, imageLink: subJson["image_url"].stringValue, summary: subJson["news_text"].stringValue, date: subJson["date"].stringValue)


        recentArray.append(newNewsObject)
    }

    arrayNews.append(recentArray)

error message

immutable value of '[(News)] only has mutating members named append

2 Answers 2

5

With

var arrayNews = Array<Array<News>>()

you declare that you will have an array of arrays.

But then you append a new instance of a News object which is not an array.

So you should probably change your arrayNews variable to be an array of News objects:

var arrayNews = [News]()
Sign up to request clarification or add additional context in comments.

2 Comments

i've added a test of the answer to my question, i getting a new error
Because you're using let, it declares a constant that you can't modify. You should use a variable (var) instead.
4

arrayNews expects Array elements but you provide it with a News elements.

You can use the following creation of your current section array and then add it to your multi-dimensional array:

let sectionArray = [News]()
sectionArray.append(newNewsObject)
arrayNews.append(sectionArray)

2 Comments

sectionArray.append(newNewsObject) arrayNews.append(sectionArray) should they both be in the loop?
well logically no, the section array should be in the loop and then added to the main array outside this loop

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.