在 Objective-C 中,我习惯于声明连接到 Interface Builder 的属性
@property (nonatomic, weak) IBOutlet UIView *myView;
现在我有一个使用新的 XCode 可空性属性的类。为了保持与 Swift 的兼容性,IBOutlet
应该具有什么可空性属性?根据 Apple 的“Using Swift with Cocoa and Objective-C”:
When you declare an outlet in Swift, you should make the type of the outlet an implicitly unwrapped optional. This way, you can let the storyboard connect the outlets at runtime, after initialization. When your class is initialized from a storyboard or xib file, you can assume that the outlet has been connected.
那么这是否意味着导出应该在 Objective-C 中声明为 nonnull
?
最佳答案
如果您的类是用 Swift 编写的,则不能使用非可选属性,否则编译器会提示该属性从未初始化。这就是为什么 Apple 建议将其声明为隐式解包可选,因为一旦你的对象被初始化,你就可以确定该属性包含一个值(除非你有一个悬空的 socket ,顺便说一下......)
当从 Objective-C 导出时,您可以将其标记为 nonnull
并且它将作为非可选属性出现在 Swift 中,这在这种情况下很好。请注意,您不能同时使用 nonnull
和 weak
。
所以你可以这样做:
@property (nonatomic, strong, nonnull) IBOutlet UIView *subview;
// Exported to Swift as @IBOutlet var subview: UIView
或
@property (nonatomic, weak, nullable) IBOutlet UIView *subview;
// Exported to Swift as @IBOutlet weak var subview: UIView?
如果出于某种原因您仍然希望将该属性作为隐式解包的可选属性导出到 Swift,您可以将该属性标记为 null_resettable
或 null_unspecified
。这并不是它们真正的目的,但它仍然会产生预期的结果。参见 this blog post有关这些注释的更多信息。
@property (nonatomic, weak, null_unspecified) IBOutlet UIView *subview;
// Exported to Swift as @IBOutlet weak var subview: UIView!
关于ios - IBOutlet 属性应该标记为可空还是非空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38644430/