1
votes

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
  }
]
1
In Swift, you can use a Bool? variable. - Amadan
Please give an example of the JSON that's causing you problems - Ashley Mills
Swift Tip: In your case, there's no need to declare CodingKeys. Set decoder.keyDecodingStrategy = .convertFromSnakeCase instead. Also, use let in your struct rather than var - Ashley Mills
@AshleyMills i have add JSON return from server in my post. i have question about, if sensor in unknown value, what should i return in JSON ? String type or Bool type ? - Anh Le
@AshleyMills if PHP return String type ( ON/OFF/Unknown) value, in Xcode i define String type to get the status. is this a good way to know 3 states of sensor ? - Anh Le

1 Answers

1
votes

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.