ios - 在 Swift 中对 @objc 类中的变量进行延迟初始化

标签 ios objective-c swift

我正在尝试对 Swift 中的类中的数组使用惰性初始化。 当我为类使用 @objc 声明时,为了在 objective-c 中使用它,我遇到了编译错误。当我只使用没有@objc 的类时,我可以毫无问题地编译它。

我收到错误:

@objc class MyClass {
    @lazy var arr : String[] = String[]()
}

Error generated

对于以下代码,我没有得到任何错误:

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/

相关文章:

ios - 无法将类型 'UITableViewCell' 的值转换为 '(AppName).(CustomCellName)'

objective-c - 用户清空垃圾时通知?

ios - 将 double 组附加到 Swift 中的邮件

ios - 使用 Swift 检查 subview 是否在 View 中

iphone - 相机照片保存在文档文件夹中,并在 iPhone 的桌面 View 中显示名称和 View

ios - MKMapView 检测何时单击注释气球

ios - GPSDictionary 返回 nil,uiimage 的元数据中没有 exif 位置数据

iOS 交互式 UILocalNotifications

ios - UISearchController 搜索框在点击时向下移动

ios - 导航栏隐藏在 SwiftUI 中不起作用