I have a struct Event
that gets initialized with a time and a value.
The value
property's type is decided at the time the event is created. It can be one of either an Int
or Double
primitive.
How should I implement this in Swift?
I want to be able to create a new Event
object like so:
let event = Event(time: Date.init(), value: EventValue<Double>(40.3467))
I found this but I can't make it out.
I have experimented with so many permutations of this and the best I can do is
struct Event {
let time: Date
var value: EventValue? // This line 'requires arguments in <...>'
}
struct EventValue <T> {
let value: T?
}
Add generic parameter to your Event
struct too and then use this type for parameter of EventValue
struct Event<T> {
let time: Date
var value: EventValue<T>?
}
then just initialize EventValue
without specifing type, since compiler allows you to pass just value corresponding to generic parameter constraint. And since your parameter has no constraints, it is equal to Any
, so you can pass any type
let event = Event(time: Date.init(), value: EventValue(value: 40.3467))
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