Fast protocol and weak links with class

If I have a protocol:

protocol SomeProtocol {
    func doSomething()
}

and in the helper class, I have a link to a protocol variable:

class someClass {
    var delegate: SomeProtocol? 
}

since it’s SomeProtocolnot marked : class, he suggested that it delegatecould be anything, and in the case of value types (structs and enums) there is no need weak var, because value types cannot create strong links. In fact, the compiler does not allow weak varanything but class types.

However, nothing prevents you from setting the class as a delegate, and if the protocol is not marked : class(since the SomeProtocol is),weak var` cannot be used and creates a save loop.

class MyClass: NSObject, SomeProtocol {
    func doSomething() { }
}

struct MyStruct: SomeProtocol {
    func doSomething() { }
}

let someClass = SomeClass()
let myStruct = MyStruct()
someClass.delegate = myStruct 
// After myStruct gets assigned to the delegate, do the delegate and the struct refer to the same instance or does the struct get copied?D

let myClass = MyClass()
someClass.delegate = myClass // can't use weak var so myClass is retained

, : class? , , , ?

+4
2

Right. , , weak ().

+1

: class - . delegate = nil deinit .

, NSOperation, SomeClass, , SomeProtocol:

protocol SomeProtocol {
    func doSomething()
}

class SomeClass {
    var delegate: SomeProtocol?
}

class CustomOperation: NSOperation {
    let foo: SomeClass
}

, :

class SomeProtocolImplementation: SomeProtocol {
    func doSomething() {
        print("Hi!")
    }
}

foo init():

class CustomOperation: NSOperation {
    let foo: SomeClass

    override init() {
        foo = SomeClass()
        foo.delegate = SomeProtocolImplementation()
        super.init()
    }
}

. deinit:

    deinit {
        foo.delegate = nil
    }

, CustomOperation , foo.delegate nil, . , , SomeClass SomeProtocolImplementation .

0

All Articles