2

I am having trouble understanding why I cannot access elements in an array after using .append

I declare an empty array here...

var entries:Array<Entry> = []

I then add entries to the array here...

var json = self.JSONParseArray(data)
for(var i = 0; i < json.count; i++)
{
    let fName = json[i]["FirstName"] as String
    let lName = json[i]["LastName"] as String
    let sC = json[i]["SelectionCode"] as String
    let id = json[i]["ID"] as String
    let iURL = json[i]["ImageURL"] as String
    let currEntry:Entry = Entry(fn: fName, ln: lName, sC: sC, id: id, img: iURL)
    self.entries.append(currEntry)
}

But when I call the .count method here...

println(self.entries.count)

I get "0" as the output as if no elements are added to the array.

The object is defined here...

class Entry {
    var dbID:String
    var firstName:String
    var lastName:String
    var selectionCode:String
    var imageLink:String

    init(fn:String, ln:String, sC:String, id:String, img:String){
        firstName = fn
        lastName = ln
        selectionCode = sC
        dbID = id
        imageLink = img
    }
}

So when I try to access an element in the array is get the error message...

fatal error: Cannot index empty buffer

I have set a breakpoint after the loop that creates and appends the objects and they exist in the debugger locals at the correct indices but are not accessible.

Thanks in advance!

1 Answer 1

2

Hey there is a better way to do this. All you are doing in here mapping from some value to other value. If you are mapping something you should consider using map function. Here is how to do it:

let jsonArray = self.JSONParseArray(data)
let entries: [Entry] = jsonArray.map { json: [NSObject: AnyObject] in
    let fName = json["FirstName"] as String
    let lName = json["LastName"] as String
    let sC = json["SelectionCode"] as String
    let id = json["ID"] as String
    let iURL = json["ImageURL"] as String
    return Entry(fn: fName, ln: lName, sC: sC, id: id, img: iURL)
}
Sign up to request clarification or add additional context in comments.

Comments

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.