I want to convert a value might be string or number to number finally by property wrapper.
For example:
"12" -> 12
12 -> 12
I achieved it by specific type Int
, Double
etc. (with below code, change T to specific type):
import Foundation
@propertyWrapper
struct NumericOrString<T: Numeric & Decodable> {
var wrappedValue: T?
init(wrappedValue: T?) {
self.wrappedValue = wrappedValue
}
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let value = try? container.decode(String.self) {
wrappedValue = T(value) // if T is Double then Double(value) works.
} else if let value = try? container.decode(T.self) {
wrappedValue = value
} else {
wrappedValue = 0
}
}
}
But generic type should be the right direction. So I tried the code above by generic type.
The issue is in this part:
wrappedValue = T(value)
No exact matches in call to initializer
.
So what can I do right now is:
if T.self is Double.Type {
wrappedValue = Double(value) as? T
}
if T.self is Int.Type {
wrappedValue = Int(value) as? T
}
Then I have to add many if
s to check the type.
Not sure if Numeric
is the right one for both String
and Numeric
, Any better solutions?