Search code examples
swiftmodulepublicaccess-control

Is it possible to edit the value of a public variable from another module?


Can you edit the value of a public variable from another module or does that variable have to be open.


My understanding of public/open in swift 3 is:

  • Public classes can be made in another module but only open classes can be subclassed in another module.
  • Public functions can be called in another module but only open functions can be overwritten in another module.
  • But I am unsure about about variables.

Solution

  • You most definitely can! Here is a great way you can accomplish it:

    In the module that contains the variable that you wish to manipulate:

    // Must be declared globally
    public var someValue = "hi"
    

    In a different module that you wish to manipulate the variable from:

    // Initialize the module that holds the variable you want to manipulate
    var myModule = SomeModule()
    
    // Manipulate the variable (someValue)
    myModule.someValue = "bye"
    

    The variable someValue will now have a value of "bye"