我正在尝试对 Swift 中的类中的数组使用惰性初始化。 当我为类使用 @objc 声明时,为了在 objective-c 中使用它,我遇到了编译错误。当我只使用没有@objc 的类时,我可以毫无问题地编译它。
我收到错误:
@objc class MyClass {
@lazy var arr : String[] = String[]()
}
对于以下代码,我没有得到任何错误:
class MyClass {
@lazy var arr : String[] = String[]()
}
谢谢你的帮助!
最佳答案
在第一种情况下,我认为它是桥接代码生成器中的错误 Developer forum .
If anything which is not objective-C compatible compiler won't generate it's objective-C equivalent (it won't give Error), For example if you have a Generics or tuple that are not supported in objective-C compiler is not going to generate objective-C equivalent for this also it won't give error.
在第二种情况下,您不包括 @objc ,来自苹果文档:
A Swift class or protocol must be marked with the @objc attribute to be accessible and usable in Objective-C. This attribute tells the compiler that this piece of Swift code can be accessed from Objective-C.If your Swift class is a descendant of an Objective-C class, the compiler automatically adds the @objc attribute for you.
因此不包含此类(不可访问),因此不会出错。
关于ios - 在 Swift 中对 @objc 类中的变量进行延迟初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24483652/