我想存储传感器的状态(真/假/未知),我创建了PHP API以返回JSON值而没有任何问题,但是我不能存储空值NULL
值(零值swift)在Bool变量中。在这种情况下,是否需要定义var String来存储 ON / OFF / Unknown 值,还是可以使用Bool var来存储true/false/nil
?
我用Codable定义Struct
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"
}
}
下面是存储从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)
我添加了来自服务器的JSON返回
[
{
"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
}
]
答案 0 :(得分:1)
如果传感器具有三种状态,则使用布尔值不是一个好方法,而是可以使用整数标志来告知传感器状态。