[英]inheritance from non-protocol type 'UIViewController' @objc protocol User: UIViewController
When we declare an optional property to a protocol it needs to be marked with @objc
attribute.当我们向协议声明可选属性时,需要用
@objc
属性对其进行标记。
The protocol is constrained to a class of type UIViewController
.该协议被限制为 UIViewController 类型的
UIViewController
。
@objc protocol User: UIViewController {
@objc optional var userImage: UIImage {get set}
}
I get the below error.我收到以下错误。 How can I constraint the protocol to the
UIViewController
and have optional property along with it?如何将协议约束到
UIViewController
并具有可选属性?
error: inheritance from non-protocol type 'UIViewController'
@objc protocol User: UIViewController {
Restricting protocols to certain classes is a Swift-only feature, so the @objc
declaration here is incompatible with that restriction.将协议限制为某些类是 Swift 独有的功能,因此此处的
@objc
声明与该限制不兼容。
Secondly, you might want to declare you property as an optional ( UIImage?
), as this will match the optionality of the requirement.其次,您可能希望将您的属性声明为可选(
UIImage?
),因为这将符合要求的可选性。
If you want optional properties in Swift, then you can add default implementations for them如果您想要 Swift 中的可选属性,那么您可以为它们添加默认实现
protocol User: UIViewController {
var userImage: UIImage? { get set }
}
extension UIViewController {
var userImage: UIImage? {
get { nil }
set { /* do nothing */ }
}
However this will make your class conformers non-objc, thus you won't be able to use them from Objective-C.但是,这将使您的 class 符合非 objc,因此您将无法从 Objective-C 使用它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.