Search code examples
iosswiftswitch-statementtype-alias

Calling a function that returns a typealias value inside another function


Currently we have a class with a function that returns a typeAlias as a value:

class NotificationDetailFactory {

   typealias T = UIViewController & NotificationDetailType

    func getNotificationType(notificationType:PushNotificationDetail?) -> T? {

        switch notificationType?.type! {
        case .notice:
            let notificationVC = NoticeViewController()
            notificationVC.notificationType = notificationType
            return notificationVC
        case .promotion:
            let promotionVC = PromoViewController()
            promotionVC.notificationType = notificationType
            return promotionVC
}
}

The return values in the switch statement are what need to be accessed (ie, notificationVC, promotionVC). In a view controller the "getNotifcationType" function is being called:

 let factory = NotificationDetailFactory()

 func goToDetailView(notificationType: PushNotificationDetail) {

        switch factory.getNotificationType(notificationType: notificationType){

        case  notificationVC:
            self.presentViewController("BGMDetailNotifications", nextModule: "notice", showInNavigationController: true, showContainer: false, data: [:], animation: nil)
        case paymentVC:
            self.presentViewController("BGMDetailNotifications", nextModule: "payment", showInNavigationController: true, showContainer: false, data: [:], animation: nil)
} }

The problem that is occurring is when we try to compile the project, an error pops up next to each case statement in the 2nd portion of code that reads:

Use of unresolved identifier 'notificationVC'

where the VC is whatever VC is trying to be accessed in the getNotificationType function. My guess its acting this way because its returning a typAlias for the first function. Whats the best way to access these VCs from the first function?


Solution

  • You have to check their types.

    let vc = factory.getNotificationType(notificationType: notificationType)
    switch vc {
        case is NoticeViewController:
            self.present(vc, nextModule: "notice", ...)
            // here goes your code for NoticeViewController case
        case is PromoViewController:
            self.present(vc, nextModule: "payment", ...)
            // here goes your code for PromoViewController case
    }