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

2

16

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}
}
Handcuff answered 9/6, 2018 at 8:2 Comment(0)
K
36

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?
}
Kyanite answered 9/6, 2018 at 8:38 Comment(0)
J
0

Add 'objc' to the protocol definition and the concrete class type and you can use 'weak' inside the protocol. Also ensure the concrete class conforms to NSObject i.e.

@objc protocol Calculation : AnyObject
{
  weak var viewModelDelegate: CalculationsViewModel? { get set }
}

@objc final class CalculationsViewModel: NSObject, ObservableObject
{
}
Jadda answered 23/6, 2023 at 12:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.