Anh Le
Anh Le

Reputation: 11

define unknown value from JSON with Bool type

I want to store status (true/false/unknown) of the sensor, I have created php API to return JSON value without any issues but I can't store empty value, NULL value (nil value in swift ) in Bool variable. In this case, whether I need to define var String to store ON/OFF/Unknown value or I can use Bool var to store true/false/nil?

I define Struct with Codable

struct nodedata: Codable {
var nodeName: String
var nodeID: String
var temperature: Float
var humidity: Float
var relayStatus: Bool
var lightStatus: Bool
var hallStatus: Bool
var smokeStatus: Bool
var pirStatus: Bool
enum CodingKeys: String, CodingKey {
        case nodeName = "node_name"  //Custom keys
        case nodeID = "node_id"
        case temperature = "temp"
        case humidity = "hum"
        case relayStatus = "relay_status"
        case lightStatus = "light_status"
        case hallStatus = "hall_status"
        case smokeStatus = "smoke_status"
        case pirStatus = "pir_status"
    }
}

below is the class to store value get from JSON

class DataManager {
    var nodes = [nodedata]()    // i write main code to store JSON only...
guard let data = data else { return }   // data get from URLSession
                        print(data)
                        let decoder = JSONDecoder()
                        self.nodes = try decoder.decode([nodedata].self, from: data)

I add JSON return from server

[
  {
    "node_name": "SVIN03",
    "node_id": "y2cfwecrw3hqznuxmfvf",
    "temp": 2132,
    "hum": 111,
    "pir_status": false,
    "smoke_status": false,
    "light_status": false,
    "hall_status": false,
    "relay_status": false
  },
  {
    "node_name": "SVIN04",
    "node_id": "aj2w1aljw8nd65ax79dm",
    "temp": 0,
    "hum": 0,
    "pir_status": false,
    "smoke_status": false,
    "light_status": false,
    "hall_status": false,
    "relay_status": false
  },
  {
    "node_name": "SVIN05",
    "node_id": "mwmfl2og2l8888fjpj2d",
    "temp": 999,
    "hum": 0,
    "pir_status": true,
    "smoke_status": false,
    "light_status": false,
    "hall_status": false,
    "relay_status": false
  }
]

Upvotes: 1

Views: 733

Answers (1)

Sunil Kumar
Sunil Kumar

Reputation: 91

If you have three states of the sensor, its not a good way to use Boolean, instead you can use integer flags, which tells sensor states.

Upvotes: 1

Related Questions