user6720691 user6720691 - 8 months ago 52
Swift Question

Switch using array not running?

For some reason my program refuses to run no matter what I do. Right now the code below gives me error

EXC_BAD_INSTRUCTION (code=EXC_BAD_i386_INVOP, subcode=0x0)

the code:

var array = [String]()
array[0] = "lmao"
switch array[0] {

case "lmao":




You are not allocating any space in the array - it is empty, so accessing element 0 causes an error. Use array.append("lmao") rather than array[0] = "lmao".

Alternatively, if you know exactly how many elements you need (say, 10) use

var array = [String](repeating: "", count: 10)

as your declaration, then you can directly set array[0] through to array[9]. You'll still get an error accessing array[10], because the array does not have 11 members...