I want to create an instance of a WeatherKit UVIndex struct.
This is how it is defined in the Apple source code (excerpt):
public struct UVIndex {
public var value: Int
public var category: UVIndex.ExposureCategory
// ...
}
extension UVIndex : Codable {
// ...
public init(from decoder: Decoder) throws
}
Now, for my SwiftUI preview I want to create a dummy instance of a UVIndex. I tried:
let uvIndex = UVIndex(value: 2, category: UVIndex.ExposureCategory(rawValue: "low"))
However it refuses to be initialised in that way, the error message says:
Extra arguments at positions #1, #2 in call
Main question:
How can I get a UVIndex instance for testing?
Secondary question:
How did Apple manage to hide away the default struct initialiser?
There is no public initializer for UVIndex
with parameters for the properties. Most likely there is a private initializer used within WeatherKit. Apple didn't intend for anyone to create instances of UVIndex
by passing in values for the properties.
Since UVIndex
supports Codable
, you can obtain an instance of UVIndex
through WeatherKit and use a JSONEncoder
to encode the instance and then look at the resulting JSON.
Using that JSON as a reference, you can create your own JSON string with the values you need. Then create a JSONDecoder
with your JSON and use the init(from:)
of UVIndex
to create your own instance.
Currently the JSON for an encoded UVIndex
is of the form:
{
"category": "low",
"value": 0
}
Of course the "category" value can be one of the UVIndex.ExposureCategory
values.
The "value" property is likely an integer in the range 0...11.