1

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.
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Lewis Black
  • 957
  • 2
  • 8
  • 22

1 Answers1

1

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"

Garret Kaye
  • 2,412
  • 4
  • 21
  • 45
  • Really appreciate this, Would that mean there's no difference between a open var and public var? (and the difference between open and public is just for functions and classes) – Lewis Black Jan 05 '17 at 16:20
  • Actually there are minor differences between `public` and `open` vars, the main one being `open` vars are subclass-able outside the module while `public` vars are not. @Martin R does a great job of explaining it here: http://stackoverflow.com/questions/38947101/what-is-the-open-keyword-in-swift – Garret Kaye Jan 05 '17 at 16:47