M2L9 crash assign String to array

Hello, ¿how are you? I have a question please!. Why if assign String to array app crash?
in line: array?[0] = “horse”

If only use append is all okay.

//
//  ContentView.swift
//  M2L9Challenger
//
//  Created by Orlando J on 22-07-23.
//

import SwiftUI

struct ContentView: View {
    
    @State var array:[String]?
    
    var body: some View {

        VStack {
            
            HStack {
                Button("Set Nil") {
                    //Code
                    setNilButton()
                }
                .foregroundColor(Color.white)
                .padding()
                .background(Color.blue)
                .cornerRadius(12)
                
                Button("AddString") {
                    // marks: add string
                    addStringButton()
                }
                .foregroundColor(Color.white)
                .padding()
                .background(Color.blue)
                .cornerRadius(12)
            }
            if array == nil {
                Text("Touch second button") } else {
                                List(array!, id:\.self) { item in
                                    Text(item)
                                }
                }
        }
    }
    
    func addStringButton() {
        array = [String]()
        array?[0] = "horse"
        array?.append("Ball")
        array?.append("Doll")
        
    }
    
    func setNilButton() {
        array = nil
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Thanks a lot!!

Is there a specific reason your array is optional? Overall there’s no reason it should be nil, instead you should clear the items in the array, with array = [] which erases all the items in the array but the array exists. And instead of checking if the array is nil as your if statement, you would check array.isEmpty

Also append is the correct way to add items to the end of an array, not the way you’re currently doing it, for this reason:

array?[0] = “horse” this line crashes, because it’s first accessing the 0 index in the array, which has nothing, so you get the crash with the message “Fatal error: Index out of range”, with that it’s already crashed, and it’s not even completing the part of setting equal to horse.

1 Like