import Foundation enum TemperatureValue { case notFound case invalidMeasurement case value(Double) init(byte: UInt8) { switch byte { case 0: self = .notFound case 1: self = .invalidMeasurement default: self = .value(Double(byte) * 0.5 - 40) } } var byte: UInt8 { switch self { case .notFound: return 0 case .invalidMeasurement: return 1 case .value(let double): let value = Int(double + 40) * 2 return UInt8(clamping: value) } } var optionalValue: Double? { if case .value(let val) = self { return val } return nil } var isValid: Bool { if case .value = self { return true } return false } var text: String { switch self { case .notFound: return "No sensor" case .invalidMeasurement: return "Invalid" case .value(let value): return String(format:" %.1f°C", value) } } } extension TemperatureValue: Codable { init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let byte = try container.decode(UInt8.self) self.init(byte: byte) } func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(byte) } }