I am working on mix and match iOS source code. I have implemented codable for swift data model class which reduces the burden of writing parser logic. I tried to conform my objective c class to codable protcol which in turn thrown an error "Cannot find protocol declaration for 'Codable'". Is there any way to use this swift protocol into objective c class? Or Is there any other objective c api that provides the same capability as Codable? The idea is to make the parsing logic same across swift and objective c classes.
Codable allows you to insert an additional clarifying stage into the process of decoding data into a Swift object. This stage is the “parsed object,” whose properties and keys match up directly to the data, but whose types have been decoded into Swift objects.
Remember, Swift's String , Int , and Bool are all Codable ! Earlier I wrote that your structs, enums, and classes can conform to Codable . Swift can generate the code needed to extract data to populate a struct's properties from JSON data as long as all properties conform to Codable .
The simplest way to make a type codable is to declare its properties using types that are already Codable . These types include standard library types like String , Int , and Double ; and Foundation types like Date , Data , and URL .
Codable is a type alias for the Encodable and Decodable protocols. When you use Codable as a type or a generic constraint, it matches any type that conforms to both protocols.
Yes, you can use Codable together with Obj-C. The tricky part is that because Obj-C can't see Decoder
, so you will need to create a helper class method when you need it to be allocated from Obj-C side.
public class MyCodableItem: NSObject, Codable {
private let id: String
private let label: String?
enum CodingKeys: String, CodingKey {
case id
case label
}
@objc public class func create(from url: URL) -> MyCodableItem {
let decoder = JSONDecoder()
let item = try! decoder.decode(MyCodableItem.self, from: try! Data(contentsOf: url))
return item
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(String.self, forKey: .id)
label = try? container.decode(String.self, forKey: .label)
super.init()
}
required init(coder decoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class LoginDataModel: NSObject ,Codable {
@objc var stepCompleted: String?
@objc var userID: Int?
@objc var authkey: String?
@objc var type, status: String?
enum CodingKeys: String, CodingKey {
case stepCompleted = "step_completed"
case userID = "user_id"
case authkey
case type, status
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With