swift protocol 'weak' cannot be applied to non-class type

前端 未结 5 2294
误落风尘
误落风尘 2020-12-05 04:00

I\'m a bit confused. What\'s the difference between protocol A : class { ... } and protocol A{ ... }, and which one we should use in swift?

<
相关标签:
5条回答
  • 2020-12-05 04:20

    protocol CustomProtocolName : NSObjectProtocol{ .... }

    0 讨论(0)
  • 2020-12-05 04:28
    protocol A : class { ... }
    

    defines a "class-only protocol": Only class types (and not structures or enumerations) can adopt this protocol.

    Weak references are only defined for reference types. Classes are reference types, structures and enumerations are value types. (Closures are reference types as well, but closures cannot adopt a protocol, so they are irrelevant in this context.)

    Therefore, if the object conforming to the protocol needs to be stored in a weak property then the protocol must be a class-only protocol.

    Here is another example which requires a class-only protocol:

    protocol A { 
        var name : String { get set }
    }
    
    func foo(a : A) {
        a.name = "bar" // error: cannot assign to property: 'a' is a 'let' constant
    }
    

    This does not compile because for instances of structures and enumerations, a.name = "bar" is a mutation of a. If you define the protocol as

    protocol A : class { 
        var name : String { get set }
    }
    

    then the compiler knows that a is an instance of a class type to that a is a reference to the object storage, and a.name = "bar" modifies the referenced object, but not a.

    So generally, you would define a class-only protocol if you need the types adopting the protocol to be reference types and not value types.

    0 讨论(0)
  • 2020-12-05 04:33

    Or you can type like this

    @objc protocol A { ... }
    

    then you can make a weak delegate reference

    0 讨论(0)
  • 2020-12-05 04:36

    You can make the protocol derive from any class type like NSObject, or AnyObject. e.g :

    protocol TopNewsTableDelegate  : AnyObject{
      func topNewsTableDidLoadedStories()
    }
    
    0 讨论(0)
  • 2020-12-05 04:39

    If you are using Swift 4 and later

    protocol A : AnyObject { ... }
    
    0 讨论(0)
提交回复
热议问题