Array of Structs

I put this piece of code in the playground on XCODE 7.3 and got the following error: EXC_BAD_INSTRUCTION** I would appreciate any assistance.

import UIKit

struct Student {
var name: String
var age: Int
var GPA: Double
}

var myStudent = [Student]()

myStudent[0].name = "John Doe" // **Error: EXC_BAD_INSTRUCTION**
myStudent[1].name = "Jane Doe"

Thanks in advance

edited by moderator to preserve code formatting

You’ve created myStudent as an array of Student structs, but it’s an empty array. When you call myStudent[0] you’re trying to get the first Student from an array with no students in it, and that’s a bad instruction. You need there to be something in an array in order to access it - unlike a Dictionary, which can return the optional value nil if there’s no value for a key, an array must always return a value for the subscripted index or your code will crash.

You could do

var students = [Student](count: 2, repeatedValue: Student())

but to do so, you’d need to provide default values for the variables. Personally, I don’t think they should all be variables, but I changed my name one time, so maybe I’m wrong. :slightly_smiling:

1 Like