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

0

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

I tried this but it did not 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
      }
   }
    
asked by anonymous 05.04.2018 / 14:56

3 answers

1

Dear colleague,

In Swift the way to do all the validation of an optional variable is to use the 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 assigning the value of the response.result.value to the result constant (in that case it will work as a local variable) and if the result is null it falls into the else.

    
09.05.2018 / 20:47
0

I found the solution to my problem I do not know if it's the correct 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
       }
    
05.04.2018 / 15:41
0

Just treat how you would treat a response 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]]
    
07.05.2018 / 22:39