[swift-users] Stored Property on Protocol Extension

Tanner Nelson me at tanner.xyz
Sun Sep 11 20:12:53 CDT 2016

Hey Swift Users,

I was wondering how you all work around not being able to add stored properties in extensions (especially protocol extensions).

I ran into an issue recently where I needed an internal stored variable for a protocol, but I didn't want the conformer to worry about implementing the variable.

I ended up using something like this to achieve the effect.

    extension MyProtocol {
        private var address: String {
            mutating get {
                var id = ""
                withUnsafePointer(to: &self) { id = "\($0)"}
                return id

        var myStoredVar: Bool {
            mutating get {
                return _storage[address] ?? false
            set {
                _storage[address] = newValue

Obviously not ideal, but I don't see another way to achieve this besides subclassing (which has its own problems for my situation).

Wondering if anyone has run into this and come up with a better solution or other type of work around.


More information about the swift-users mailing list