Reputation: 511
I am doing my first steps with the Codable Protocol and getting a Build Error when trying to mix my struct with a custom getter. How would I solve this problem. Do I have to write custom decode and encode functions?
struct MyStruct: Codable {
var variable: String? {
get { return variable?.lowercased() }
}
private enum CodingKeys: String, CodingKey {
case variable = "variable1"
}
}
UPDATE: WORKAROUND
I found one workaround, which is not optimal but it does the job, by introducing a private variable holding the 'real' data:
struct MyStruct: Codable {
private var _variable: String?
var variable: String? {
get { return _variable?.lowercased() }
}
private enum CodingKeys: String, CodingKey {
case _variable = "variable1"
}
}
Upvotes: 1
Views: 1673
Reputation: 1994
The reason you need to use this "workaround" is because computed properties are not meant to store data. According to the documentation, they, "...do not actually store a value. Instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly." - The Swift Programming Language
Computed properties are not intended to store values. But what you can do is to use a stored property, and then use didSet
to modify it at the time it is being set. This has the added advantage of efficiency, since you'll only lowercase it once when it is set, rather than every time it is accessed.
struct MyStruct: Codable {
var variable: String? {
didSet {
variable = variable?.lowercased()
}
}
}
Upvotes: 1