guys!
I'm trying to make a protocol extension that will go through struct/class/enum and convert its properties/rawValue to NSData using Mirror.
These types can contain another structs/enums/classes which are conforming to DataConvertable protocol too, or just Uint8 and Uint16, which can be converted to NSData by data() function.
It looks ok for me for structs and classes, but I still have some problems with enums.
protocol DataConvertable {
func data() -> NSData?
}
extension DataConvertable {
func data() -> NSData? {
let resultData = NSMutableData(capacity: sizeofValue(self))!
let mirror = Mirror(reflecting: self)
guard let displayStyle = mirror.displayStyle else { return nil }
switch displayStyle {
case .Enum:
if let enumValue = self as? RawRepresentable {
resultData.appendData(enumValue.rawValue.data())
}
case .Struct, .Class:
for case let(_, value) in mirror.children {
if let uint16Value = value as? UInt16 {
resultData.appendData(uint16Value.data())
} else if let uint8Value = value as? UInt8 {
resultData.appendData(uint8Value.data())
} else if let subValue = value as? DataConvertable {
resultData.appendData(subValue.data())
}
}
default:
break
}
return NSData(data: resultData)
}
}
This line is not working.
if let enumValue = self as? RawRepresentable
How can I manage it? Do you have any ideas?
Thanks!
Aucun commentaire:
Enregistrer un commentaire