Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify a generic value argument as a parameter of an object initialization call

Tags:

generics

swift

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?
}
like image 598
elight Avatar asked Jan 18 '19 19:01

elight


1 Answers

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))
like image 199
Robert Dresler Avatar answered Sep 28 '22 16:09

Robert Dresler