简体   繁体   中英

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.

The protocol is constrained to a class of type 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?

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.

Secondly, you might want to declare you property as an optional ( UIImage? ), as this will match the optionality of the requirement.

If you want optional properties in Swift, then you can add default implementations for them

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM