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

            Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

            Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

            How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page