【问题标题】:Swift dynamic type Debug/ReleaseSwift 动态类型 Debug/Release
【发布时间】:2017-08-03 09:55:17
【问题描述】:

我有这段代码:

class NotificationsController: NSObject {

    static var classNotifier: AnyClass {
        if #available(iOS 10, *) {
            return UNUserNotificationCenter.classForCoder()
        } else {
            return UILocalNotification.classForCoder()
        }
    }

    static func foo() {
        NotificationsController.classNotifier.foo()
    }

}

地点:

protocol Notificable: class {
   static func foo()
}

extension UNUserNotificationCenter: Notificable {

   static func foo() {
      // do something
   }

}

extension UILocalNotification: Notificable {

   static func foo() {
      // do something
   }

}

在调试模式下构建工作正常。
当我在发布模式下构建(用于归档)时,编译器说 AnyClass 没有一个名为“foo”的函数。

现在,我知道如果我删除发布优化构建作品,但我认为这是错误的解决方案。

其他解决方案?

【问题讨论】:

  • classNotifier 返回一个 Classfoo 是一个实例方法,对吧?另外,我可能会将您的协议称为Notifiable
  • 你试过(NotificationsController.classNotifier as AnyObject).foo()吗?
  • 你有没有试过让协议中的 foo 像 static func foo 一样通知静态?
  • 不应该是static var classNotifier: Notificable in NotificationsController

标签: ios swift compiler-optimization


【解决方案1】:

一段时间后,我对代码进行了调查并重写了您的解决方案。问题与protocol Notificable 和实例函数func foo() 有关。

您尝试将此函数称为类函数而不是实例一,但出现问题。

工作解决方案示例。

protocol Notificable: class {
     static func foo()
}

extension UNUserNotificationCenter: Notificable {
    internal static func foo() {

    }
}

extension UILocalNotification: Notificable {
    internal static func foo() {

    }
}

class NotificationsController: NSObject {

    static var classNotifier: AnyClass {
        if #available(iOS 10, *) {
            return UNUserNotificationCenter.classForCoder()
        } else {
            return UILocalNotification.classForCoder()
        }
    }

    static func foo() {
        classNotifier.foo()
    }

}

【讨论】:

  • 感谢 oleg 提出的意见。实际上是我的错误,在实际代码中我已经有了静态方法(我更新了问题)。问题仍然存在
  • @LucaDavanzo NotificationsController 和 Extensions 在不同的文件中?
  • 尝试将所有这些信息放到一个类中并尝试构建。
猜你喜欢
  • 2013-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-29
  • 2023-01-11
  • 2021-06-02
相关资源
最近更新 更多