How to treat a reponse.result.value that returns as log optional([])?

Asked

Viewed 138 times

1

I am in the following situation I have a request in the Alamofire that returns me a json that may or may not have data (usually has but may not). I want to treat when Response.result.value returns optional([]).

I tried that but it didn’t work

   let json = response.result.value
   print(json)//retorna Optional[]

   if json == nil {
      //aviso o usuario que nao tenho os dados pra mostrar
   }
   else{
      //trabalho com os dados retornados
      if let json = json {
         for JSON in json {     
            //for para percorrer o objeto que me foi retornado
      }
   }
  • Only one thing, this 'json == nil' does not need, since down there you do if 'Let json = json'. if Let already checks if it is different from nil and takes the optional from it

  • It doesn’t work because I’ll never have a nil because when there’s nothing in the json it gives me a []. Oh nil doesn’t work.

3 answers

1

I found the solution to my problem I don’t know if it’s the right way but it worked.

    let json = response.result.value
       print(json?.toJSONString())//retorna Optional("[]")

       if json?.toJSONString() != "[]" {
          //trabalho com os dados retornados
          if let json = json {
             for JSON in json {     
                //for para percorrer o objeto que me foi retornado
          }
       }
       else{
          //aviso o usuario que nao tenho os dados pra mostrar
       }

1

Dear colleague,

In Swift the way to do all the validation of an optional variable is by using if Let, as shown below. This check replaces the if you did.

if let result = response.result.value{
    //faz o que voce quer aqui
}else{
    //aviso o usuario que nao tenho os dados pra mostrar
}

If the value is not null it falls into if normally by assigning the value of the result.result.value to the result constant (in this case it will work as a local variable) and if the result is null it falls into Else.

0

Just treat how you would treat a Sponse that returns an array of objects and check if it is empty.

//mockando o optional([])
let json: [Any]? = [Any]() 
if let array = json as? [[String: Any]] {
    if array.isEmpty {
        print("Não há dados para exibir")
    }
}

//mockando array de objetos
let data = "[{\"id\":1},{\"id\":2}]".data(using: String.Encoding.utf8)! 
let json2 = try? JSONSerialization.jsonObject(with: data, options: [])
if let array = json2 as? [[String: Any]] {
    if array.isEmpty {
        print("Não há dados para exibir")
    } else {
        print(array)
    }
}

//resultado:
// - Não há dados para exibir
// - [["id": 1], ["id": 2]]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.