2

Is it possible to pass the "type" of a struct as an argument? Use case below (syntax doesn't work):

// Declarations.
public protocol Event {}

public enum AwesomeEvents {
  public enum Notifications {
    public struct NotificationReceived : Event {
      ...
    }
  }
}

// Is it possible to do something like this?
func testNotifications {
  ...
  doSomethingAndCheckEventType(correctEventType: AwesomeEvents.Notifications.NotificationReceived.Type)
}

func doSomethingAndCheckEventType<T: Event>(correctEventType: T) {
  ...
  XCTestAssertTrue(someEvent is correctEventType)
}
Azria
  • 33
  • 5

2 Answers2

1

You can make use of the == operator for metatypes.

func testNotifications() {
  doSomethingAndCheckEventType(correctEventType: AwesomeEvents.Notifications.NotificationReceived.self)
}

func doSomethingAndCheckEventType<CorrectEvent: Event>(correctEventType: CorrectEvent.Type) {
  let someEvent = AwesomeEvents.Notifications.NotificationReceived()
  XCTAssert(type(of: someEvent) == correctEventType)
}
1

One possible solution:

func testNotifications {
  ...
  doSomethingAndCheckEventType(correctEventType: AwesomeEvents.Notifications.NotificationReceived.self)
}

func doSomethingAndCheckEventType<T: Event>(correctEventType: T.Type) {
  ...
  XCTestAssertTrue(someEvent is T)
}
Azria
  • 33
  • 5