我想存储传感器的状态(真/假/未知(,我已经创建了 php API 来返回 JSON 值而没有任何问题,但我无法在布尔变量中存储空值,NULL
值(swift 中的零值(。在这种情况下,我是否需要定义 var 字符串来存储ON/OFF/未知值,或者我可以使用 bool var 来存储true/false/nil
?
我用可编码定义结构
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
}
]
如果传感器有三种状态,则使用布尔值不是好方法,而是可以使用整数标志来告知传感器状态。