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
UVIndexwith parameters for the properties. Most likely there is a private initializer used within WeatherKit. Apple didn't intend for anyone to create instances ofUVIndexby passing in values for the properties.Since
UVIndexsupportsCodable, you can obtain an instance ofUVIndexthrough WeatherKit and use aJSONEncoderto 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
JSONDecoderwith your JSON and use theinit(from:)ofUVIndexto create your own instance.Currently the JSON for an encoded
UVIndexis of the form:Of course the "category" value can be one of the
UVIndex.ExposureCategoryvalues.The "value" property is likely an integer in the range 0...11.