johnson johnson - 1 year ago 51
Swift Question

How do I update the array inside a class with an extension?

I have an extension which is reading a json file, but that's not the problem. The problem is updating the array in the class with the collection view methods. When I print the array length inside the extension I get 3, but when I print it inside the class where the collection view delegate methods are it prints 0.

extension JSON{

func findmultiple(viewclass: ViewController, @noescape predicate: JSON -> Bool) -> JSON? {

if predicate(self) {
return self
else {
if let subJSON = (dictionary?.map { $0.1 } ?? array) {
for json in subJSON {

if let foundJSON = json.findmultiple(viewclass, predicate: predicate) {
let shorten = foundJSON["html"].stringValue
let firstshort = shorten.componentsSeparatedByString(" ")
let secondshort = firstshort[1].componentsSeparatedByString("\r")
let classname = secondshort[0]
if(classname == "STUDY HALL (INSTRUCT)"){
print("fsgsfg \(viewclass.importgrades.count)") //prints("STUDY HALL", "CHEMISTRY", "PHYSICS")






return nil

When I go to the class with the methods

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource{
var importClass = [String]()

func parseJSON(json: JSON){

let predicate = {
(json: JSON) -> Bool in
if let jsonID = json["class"].string where jsonID == "sg-header-heading"{

return true

return false
var backclass = ViewController()
let foundJSON = json.findmultiple(backclass, predicate: predicate)


func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell: colcell = (collection.dequeueReusableCellWithReuseIdentifier("CELL", forIndexPath: indexPath) as? colcell)!
print(importClass) //prints []
cell.classtitle.text = importClass[indexPath.item] //crashes `index out of range`

Answer Source

In your ViewController class your variable is defined as importClasses and everywhere else its importClass, is this just a typo as you should get a build error if its not.

Depending on how you are requesting the JSON you probably want to try calling collectionView.reloadData() once you have successfully retrieved the JSON.