How does one make protocols and their extensions in Swift store properties?How to have stored properties in Swift, the same way I had on Objective-C?Swift - Protocol extensions - Property default valuesSwift extension storage for protocolsHow to call Objective-C code from SwiftWhy no stored type properties for classes in swift?How can I make a weak protocol reference in 'pure' Swift (without @objc)Swift Beta performance: sorting arraysSwift: Generic ProtocolsMutating Function in Protocol Extension Where Self is UIViewControllerSwift - Protocol extensions - Property default valuesWhy must Protocol defaults be implemented via Extensions in Swift?Swift protocol with a member typed as another protocolWhen and why would i use Protocols in Swift?

How many wives did king shaul have

What are the G forces leaving Earth orbit?

Why is it a bad idea to hire a hitman to eliminate most corrupt politicians?

Why is the sentence "Das ist eine Nase" correct?

How obscure is the use of 令 in 令和?

Unlock My Phone! February 2018

How to travel to Japan while expressing milk?

Send out email when Apex Queueable fails and test it

Why didn't Boeing produce its own regional jet?

What is an equivalently powerful replacement spell for the Yuan-Ti's Suggestion spell?

How can saying a song's name be a copyright violation?

What Exploit Are These User Agents Trying to Use?

Am I breaking OOP practice with this architecture?

Where would I need my direct neural interface to be implanted?

Venezuelan girlfriend wants to travel the USA to be with me. What is the process?

In the UK, is it possible to get a referendum by a court decision?

How can a day be of 24 hours?

Is this draw by repetition?

Sums of two squares in arithmetic progressions

Can a virus destroy the BIOS of a modern computer?

What is the opposite of "eschatology"?

How could indestructible materials be used in power generation?

How to stretch the corners of this image so that it looks like a perfect rectangle?

What is a Samsaran Word™?



How does one make protocols and their extensions in Swift store properties?


How to have stored properties in Swift, the same way I had on Objective-C?Swift - Protocol extensions - Property default valuesSwift extension storage for protocolsHow to call Objective-C code from SwiftWhy no stored type properties for classes in swift?How can I make a weak protocol reference in 'pure' Swift (without @objc)Swift Beta performance: sorting arraysSwift: Generic ProtocolsMutating Function in Protocol Extension Where Self is UIViewControllerSwift - Protocol extensions - Property default valuesWhy must Protocol defaults be implemented via Extensions in Swift?Swift protocol with a member typed as another protocolWhen and why would i use Protocols in Swift?













0















The following is a workaround for the "problem" that protocols and their extensions in Swift do not store properties. It seems to "work" but I am wondering what reasons people might have for avoiding it?



fileprivate var strings: [String] = []

protocol SomeProat
func add(someString: String)


extension SomeProat
func add(someString: String)
strings.append(someString)
print(strings)




(I realise this question could be interpreted as subjective btw).










share|improve this question

















  • 2





    string is a global variable in your code, it is not inside your protocol

    – Zich
    Mar 8 at 21:11











  • Still interesting tho, thanks

    – Joseph Beuys' Mum
    Mar 8 at 21:20






  • 1





    As @Zich says, strings is a global variable. All instances of any type adopting your protocol will share the same strings, that makes it not very useful.

    – Martin R
    Mar 8 at 21:23







  • 1





    Why is people answering with comments?

    – TimTwoToes
    Mar 8 at 21:24






  • 2





    Can you please clarify what you are asking for? The title asks how to add stored properties in an extension, a possible solution are associated object, compare e.g. stackoverflow.com/q/34933928/1187415 or stackoverflow.com/q/25426780/1187415. – Or are you asking if your workaround is correct?

    – Martin R
    Mar 8 at 21:31
















0















The following is a workaround for the "problem" that protocols and their extensions in Swift do not store properties. It seems to "work" but I am wondering what reasons people might have for avoiding it?



fileprivate var strings: [String] = []

protocol SomeProat
func add(someString: String)


extension SomeProat
func add(someString: String)
strings.append(someString)
print(strings)




(I realise this question could be interpreted as subjective btw).










share|improve this question

















  • 2





    string is a global variable in your code, it is not inside your protocol

    – Zich
    Mar 8 at 21:11











  • Still interesting tho, thanks

    – Joseph Beuys' Mum
    Mar 8 at 21:20






  • 1





    As @Zich says, strings is a global variable. All instances of any type adopting your protocol will share the same strings, that makes it not very useful.

    – Martin R
    Mar 8 at 21:23







  • 1





    Why is people answering with comments?

    – TimTwoToes
    Mar 8 at 21:24






  • 2





    Can you please clarify what you are asking for? The title asks how to add stored properties in an extension, a possible solution are associated object, compare e.g. stackoverflow.com/q/34933928/1187415 or stackoverflow.com/q/25426780/1187415. – Or are you asking if your workaround is correct?

    – Martin R
    Mar 8 at 21:31














0












0








0


0






The following is a workaround for the "problem" that protocols and their extensions in Swift do not store properties. It seems to "work" but I am wondering what reasons people might have for avoiding it?



fileprivate var strings: [String] = []

protocol SomeProat
func add(someString: String)


extension SomeProat
func add(someString: String)
strings.append(someString)
print(strings)




(I realise this question could be interpreted as subjective btw).










share|improve this question














The following is a workaround for the "problem" that protocols and their extensions in Swift do not store properties. It seems to "work" but I am wondering what reasons people might have for avoiding it?



fileprivate var strings: [String] = []

protocol SomeProat
func add(someString: String)


extension SomeProat
func add(someString: String)
strings.append(someString)
print(strings)




(I realise this question could be interpreted as subjective btw).







swift protocols protected protocol-extension






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 8 at 21:08









Joseph Beuys' MumJoseph Beuys' Mum

83311030




83311030







  • 2





    string is a global variable in your code, it is not inside your protocol

    – Zich
    Mar 8 at 21:11











  • Still interesting tho, thanks

    – Joseph Beuys' Mum
    Mar 8 at 21:20






  • 1





    As @Zich says, strings is a global variable. All instances of any type adopting your protocol will share the same strings, that makes it not very useful.

    – Martin R
    Mar 8 at 21:23







  • 1





    Why is people answering with comments?

    – TimTwoToes
    Mar 8 at 21:24






  • 2





    Can you please clarify what you are asking for? The title asks how to add stored properties in an extension, a possible solution are associated object, compare e.g. stackoverflow.com/q/34933928/1187415 or stackoverflow.com/q/25426780/1187415. – Or are you asking if your workaround is correct?

    – Martin R
    Mar 8 at 21:31













  • 2





    string is a global variable in your code, it is not inside your protocol

    – Zich
    Mar 8 at 21:11











  • Still interesting tho, thanks

    – Joseph Beuys' Mum
    Mar 8 at 21:20






  • 1





    As @Zich says, strings is a global variable. All instances of any type adopting your protocol will share the same strings, that makes it not very useful.

    – Martin R
    Mar 8 at 21:23







  • 1





    Why is people answering with comments?

    – TimTwoToes
    Mar 8 at 21:24






  • 2





    Can you please clarify what you are asking for? The title asks how to add stored properties in an extension, a possible solution are associated object, compare e.g. stackoverflow.com/q/34933928/1187415 or stackoverflow.com/q/25426780/1187415. – Or are you asking if your workaround is correct?

    – Martin R
    Mar 8 at 21:31








2




2





string is a global variable in your code, it is not inside your protocol

– Zich
Mar 8 at 21:11





string is a global variable in your code, it is not inside your protocol

– Zich
Mar 8 at 21:11













Still interesting tho, thanks

– Joseph Beuys' Mum
Mar 8 at 21:20





Still interesting tho, thanks

– Joseph Beuys' Mum
Mar 8 at 21:20




1




1





As @Zich says, strings is a global variable. All instances of any type adopting your protocol will share the same strings, that makes it not very useful.

– Martin R
Mar 8 at 21:23






As @Zich says, strings is a global variable. All instances of any type adopting your protocol will share the same strings, that makes it not very useful.

– Martin R
Mar 8 at 21:23





1




1





Why is people answering with comments?

– TimTwoToes
Mar 8 at 21:24





Why is people answering with comments?

– TimTwoToes
Mar 8 at 21:24




2




2





Can you please clarify what you are asking for? The title asks how to add stored properties in an extension, a possible solution are associated object, compare e.g. stackoverflow.com/q/34933928/1187415 or stackoverflow.com/q/25426780/1187415. – Or are you asking if your workaround is correct?

– Martin R
Mar 8 at 21:31






Can you please clarify what you are asking for? The title asks how to add stored properties in an extension, a possible solution are associated object, compare e.g. stackoverflow.com/q/34933928/1187415 or stackoverflow.com/q/25426780/1187415. – Or are you asking if your workaround is correct?

– Martin R
Mar 8 at 21:31













1 Answer
1






active

oldest

votes


















3














There is no good way to do what you're asking in pure Swift on non-Apple platforms.



If you are on an Apple platform (macOS, iOS, tvOS, watchOS), and your conforming type is a class, then you can use the associated object support provided by the Objective-C runtime:



import ObjectiveC

protocol MyProtocol: class
var strings: [String] get
func add(someString: String)


private var MyProtocolSomeStringKey: UInt8 = 0

extension MyProtocol
var strings: [String]
get
return objc_getAssociatedObject(self, &MyProtocolSomeStringKey) as? [String] ?? []

set
let value = newValue.isEmpty ? nil : newValue
objc_setAssociatedObject(self, &MyProtocolSomeStringKey, value, .OBJC_ASSOCIATION_RETAIN)



func add(someString: String)
strings.append(someString)



class MyObject
extension MyObject: MyProtocol

let myObject = MyObject()
myObject.add(someString: "hello")
myObject.add(someString: "world")
print(myObject.strings)
// Output: ["hello", "world"]





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55071020%2fhow-does-one-make-protocols-and-their-extensions-in-swift-store-properties%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3














    There is no good way to do what you're asking in pure Swift on non-Apple platforms.



    If you are on an Apple platform (macOS, iOS, tvOS, watchOS), and your conforming type is a class, then you can use the associated object support provided by the Objective-C runtime:



    import ObjectiveC

    protocol MyProtocol: class
    var strings: [String] get
    func add(someString: String)


    private var MyProtocolSomeStringKey: UInt8 = 0

    extension MyProtocol
    var strings: [String]
    get
    return objc_getAssociatedObject(self, &MyProtocolSomeStringKey) as? [String] ?? []

    set
    let value = newValue.isEmpty ? nil : newValue
    objc_setAssociatedObject(self, &MyProtocolSomeStringKey, value, .OBJC_ASSOCIATION_RETAIN)



    func add(someString: String)
    strings.append(someString)



    class MyObject
    extension MyObject: MyProtocol

    let myObject = MyObject()
    myObject.add(someString: "hello")
    myObject.add(someString: "world")
    print(myObject.strings)
    // Output: ["hello", "world"]





    share|improve this answer



























      3














      There is no good way to do what you're asking in pure Swift on non-Apple platforms.



      If you are on an Apple platform (macOS, iOS, tvOS, watchOS), and your conforming type is a class, then you can use the associated object support provided by the Objective-C runtime:



      import ObjectiveC

      protocol MyProtocol: class
      var strings: [String] get
      func add(someString: String)


      private var MyProtocolSomeStringKey: UInt8 = 0

      extension MyProtocol
      var strings: [String]
      get
      return objc_getAssociatedObject(self, &MyProtocolSomeStringKey) as? [String] ?? []

      set
      let value = newValue.isEmpty ? nil : newValue
      objc_setAssociatedObject(self, &MyProtocolSomeStringKey, value, .OBJC_ASSOCIATION_RETAIN)



      func add(someString: String)
      strings.append(someString)



      class MyObject
      extension MyObject: MyProtocol

      let myObject = MyObject()
      myObject.add(someString: "hello")
      myObject.add(someString: "world")
      print(myObject.strings)
      // Output: ["hello", "world"]





      share|improve this answer

























        3












        3








        3







        There is no good way to do what you're asking in pure Swift on non-Apple platforms.



        If you are on an Apple platform (macOS, iOS, tvOS, watchOS), and your conforming type is a class, then you can use the associated object support provided by the Objective-C runtime:



        import ObjectiveC

        protocol MyProtocol: class
        var strings: [String] get
        func add(someString: String)


        private var MyProtocolSomeStringKey: UInt8 = 0

        extension MyProtocol
        var strings: [String]
        get
        return objc_getAssociatedObject(self, &MyProtocolSomeStringKey) as? [String] ?? []

        set
        let value = newValue.isEmpty ? nil : newValue
        objc_setAssociatedObject(self, &MyProtocolSomeStringKey, value, .OBJC_ASSOCIATION_RETAIN)



        func add(someString: String)
        strings.append(someString)



        class MyObject
        extension MyObject: MyProtocol

        let myObject = MyObject()
        myObject.add(someString: "hello")
        myObject.add(someString: "world")
        print(myObject.strings)
        // Output: ["hello", "world"]





        share|improve this answer













        There is no good way to do what you're asking in pure Swift on non-Apple platforms.



        If you are on an Apple platform (macOS, iOS, tvOS, watchOS), and your conforming type is a class, then you can use the associated object support provided by the Objective-C runtime:



        import ObjectiveC

        protocol MyProtocol: class
        var strings: [String] get
        func add(someString: String)


        private var MyProtocolSomeStringKey: UInt8 = 0

        extension MyProtocol
        var strings: [String]
        get
        return objc_getAssociatedObject(self, &MyProtocolSomeStringKey) as? [String] ?? []

        set
        let value = newValue.isEmpty ? nil : newValue
        objc_setAssociatedObject(self, &MyProtocolSomeStringKey, value, .OBJC_ASSOCIATION_RETAIN)



        func add(someString: String)
        strings.append(someString)



        class MyObject
        extension MyObject: MyProtocol

        let myObject = MyObject()
        myObject.add(someString: "hello")
        myObject.add(someString: "world")
        print(myObject.strings)
        // Output: ["hello", "world"]






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 8 at 21:35









        rob mayoffrob mayoff

        296k42598647




        296k42598647





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55071020%2fhow-does-one-make-protocols-and-their-extensions-in-swift-store-properties%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

            2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

            Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme