J-Dizzle
J-Dizzle

Reputation: 5153

How to share constants and variables between files in Swift

How do you share variables in Swift between files in a simple traditional way? I am aware of accessor methods -

Accessor Example

   SomeOtherClass.getMyVar()

But I am looking for just

Desired Use

    myVar

Context

So equivalent to how this works in C, with Header Files & #import... Is this possible?

Upvotes: 0

Views: 7002

Answers (4)

Vinay Krishna Gupta
Vinay Krishna Gupta

Reputation: 475

What I did in my Swift project 1: Create new Swift File 2: Create a struct and static constant in it. 3: For Using just use YourStructName.baseURL

Note: After Creating initialisation takes little time so it will show in other viewcontrollers after 2-5 seconds.

import Foundation

struct YourStructName {
        static let MerchantID = "XXX"
        static let MerchantUsername = "XXXXX"
        static let ImageBaseURL = "XXXXXXX"
        static let baseURL = "XXXXXXX"
        }

Upvotes: 1

vadian
vadian

Reputation: 285290

Importing something is not necessary in Swift.

You have two options (both declared outside any class) :

  • A global variable

    let kNAME_KEY = "name"
    let kAGE_KEY = "age
    

    to be called with

    let name = kNAME_KEY
    
  • A static variable embedded in a struct

    struct Key {
     static let Name = "name"
     static let Age = "age"
    }
    

    to be called with

    let name = Key.Name
    

The design of Swift highly recommends the way using a struct.

Upvotes: 2

J-Dizzle
J-Dizzle

Reputation: 5153

katleta3000 was correct. Hard to believe as a 'traditional' C-developer, but correct. Just define a var in a file outside of any other scope (e.g. in a class), and you can magically access it ANYWHERE.

Example

  • "var someVar = 1" in ViewController.Swift on Line 11, above the Line 13 of 'class ViewController: UIViewController {'

  • And now you can use someVar in any file within the project, e.g. use in AppDelegate.swift is fine

(Context) As a traditionalist, I cry inside at this...

Upvotes: 1

Laffen
Laffen

Reputation: 2771

I wouldn't recommend it, but to answer your question you could do the following:

class Foo {

    class var Test: String {
        return "MyString"
    }

}

class Bar {

    func someFunc(){
        print(Foo.Test)
    }

}

I'm sure someone will come along and give better examples, until then.. here you go :)

Upvotes: 1

Related Questions