SWIFT: Index out of range displaying Text but working correctly on Print

Viewed 78

i have this problem. When I want to print a value of my array on Console its OK. But when I want to print the same value of my array as the same way on Text() says Index out of range

Here is a part of my code

struct VerCajaView: View {

class X1: Codable, Identifiable {
    var operacion: String? = ""
    var fecha: String? = ""
}

class X2: Codable, Identifiable {
    var suma_ars: String? = ""
  

}

class Respuesta: Codable, Identifiable  {
    var movimientos: [X1] = []
    var Sumas : [X2] = []
}

@State var models: [X1] = []
@State var sumato: [X2] = []


var body: some View {
    
    Button(action: {
        print(sumato[0].suma_ars)
    }){
        Text(sumato[0].suma_ars ?? "Start")
    }
    

Also I retrieving my json response like

 var urlRequest: URLRequest = URLRequest(url: url)
        urlRequest.httpMethod = "GET"
        URLSession.shared.dataTask(with: urlRequest, completionHandler: { (data, response, error) in
           
             
            guard let data = data else {
                print("invalid response")
                return
            }
             
           
            do {
                          
                let resultado = try JSONDecoder().decode(Respuesta.self, from: data)
                self.models = resultado.movimientos
                self.sumato = resultado.Sumas

my json response is

{"movimientos":[{"id":"26","operacion":"Compra","fecha":"21\/07\/13"},{"id":"27","operacion":"Venta","fecha":"21\/07\/13"},{"id":"28","operacion":"Retiro","fecha":"21\/07\/13"}],"Sumas":[{"suma_ars":"-900"}]}
1 Answers

In SwiftUI views are being rendered quite often.

The first time the array is empty and the crash occurs.

Never get items from an array with index subscripting in a view rendering area.

Either use first which returns an optional

Text(sumato.first?.suma_ars ?? "Start")

or perform a check

Text(sumato.isEmpty ? "Start" : sumato[0].suma_ars)
Related