Stewart Hering
Stewart Hering

Reputation: 304

Passing variables from one swift file to another

Let's say I have 3 swift files:

fileOne.swift
fileTwo.swift
vars.swift

and let's say that my vars.swift file looks like this:

let let1 = "this is let one"
var isItTrue = false

How can I setup my code in fileOne.swift and fileTwo.swift so that I can access and modify the variables contained within the vars.swift file?

Upvotes: 3

Views: 4906

Answers (3)

aarti
aarti

Reputation: 2865

If vars.swift a file from where you will access constants you can create the constants in a struct and then access them from the other file

struct Constants {
    static let v1 = "var1"
}

file1.swift

class File1 {

  func test() {
    print( Constants.v1);
  }

}

Upvotes: 6

Arsen
Arsen

Reputation: 10951

Vars.swift

struct Vars {
    static let key1 = "value1"
    static let key2 = "value2"
}

Use:

Vars.key1

Upvotes: 0

matt
matt

Reputation: 535306

If your vars.swift file really says let let1=... right at the top level of the file, you can just access let1 from anywhere; all Swift files can see one another, and let1 is a global constant. Similarly for var isItTrue; it is a global variable and any code anywhere can see it and set it.

If what you mean is that vars.swift contains a class declaration with instance variables, then you need to get a reference to an instance in order to set those variables. You need to learn about object-oriented programming (which is what you're doing when you use Swift).

Upvotes: 0

Related Questions