Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift warning: 'weak' should not be applied to a property declaration in a protocol

Looks like weak references will be disallowed in protocols. So what am I supposed to do if I wanna add a weak reference? Any better idea?

protocol PipelineElementDelegate: class {
    func someFunc()
}
protocol PipelineElement {
    weak var delegate: PipelineElementDelegate? { get set}
}
like image 634
boog Avatar asked Jun 09 '18 08:06

boog


People also ask

What is a swift protocol?

In Swift, a protocol defines a blueprint of methods or properties that can then be adopted by classes (or any other types). We use the protocol keyword to define a protocol. For example, protocol Greet { // blueprint of a property var name: String { get } // blueprint of a method func message() }

How do you make a weak protocol Swift?

Protocols can be used for both reference types (classes) and value types (structs, enums). So in the likely case that you need to make a delegate weak, you have to make it an object-only protocol. The way to do that is to add AnyObject to the protocol's inheritance list.


1 Answers

Simply remove the weak keyword from the protocol and declare the property as weak in the conforming type instead:

class SomeClass: PipelineElement {
    weak var delegate: PipelineElementDelegate?
}
like image 150
zoul Avatar answered Nov 14 '22 19:11

zoul