1

Is it possible to create a variable in a (default implementation of a) protocol? Specifically, I have a variable required by the protocol as:

protocol SearchHandlingDelegate: class {
    ...
    var lastSearchTerm: String { get set }
    ...
}

and was hoping to have a default implementation of it in a protocol extension as:

extension SearchHandlingDelegate {
    ...
    var lastSearchTerm: String {
        set { lastSearchTerm = newValue }
        get { return lastSearchTerm }
    }
    ...
}

But this is a bottomless recursive self-call loop… I could have it return the value of another variable, but then it’s not really going to be possible to do this via a default implementation of the protocol…

Hamish
  • 78,605
  • 19
  • 187
  • 280
EndersJeesh
  • 427
  • 1
  • 4
  • 20
  • 5
    Extensions cannot add stored properties – you can however use Obj-C associated objects, see for example http://stackoverflow.com/q/25426780/2976878 (dupe?) – Hamish Mar 20 '17 at 19:02

1 Answers1

3

You can provide default implementations of get/set properties for computed values, but you can’t add storage to a type from an extension.

colinrf
  • 253
  • 1
  • 6