[swift-users] Stored Property on Protocol Extension

Daniel Dunbar daniel_dunbar at apple.com
Mon Sep 12 10:55:12 CDT 2016


> On Sep 11, 2016, at 6:12 PM, Tanner Nelson via swift-users <swift-users at swift.org> wrote:
> 
> 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

BTW, you can write `return withUnsafePointer(to: &self) { "\($0)" }` instead.

>            }
>        }
> 
>        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.

I don't have a better answer to this part.

This particular solution only works if it is ok for `_storage[address]` to potentially be reused by a new instance, though (if the old instance is deallocated and the new one is allocated in its place).

 - Daniel

> 
> Thanks!
> Tanner
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users



More information about the swift-users mailing list