目前我们有一个类,它的函数返回一个类型别名作为值:

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
}
}

switch语句中的返回值是需要访问的值(即notificationVC、promotionVC)。在视图控制器中,正在调用“getNotifcationType”函数:
 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)
} }

出现的问题是,当我们试图编译项目时,代码第二部分中的每个case语句旁边都会弹出一个错误,内容如下:
使用未解析的标识符“notificationVC”
其中VC是在getNotificationType函数中试图访问的任何VC。我猜它这样做是因为它为第一个函数返回了一个typaalias。从第一个功能访问这些VCs的最佳方式是什么?

最佳答案

你必须检查他们的类型。

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
}

关于ios - 调用一个在另一个函数中返回类型别名值的函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46651335/

10-14 18:36
查看更多