5

I am trying to create a global array (of items in a cart) in Swift so that I can access it from different pages.

Can you please point me in the right direction? declaring an array under the import statement in AppDelegate gives me the "unresolved Identifier" issue.

What should I use? How can I accomplish that? Thank you!

2 Answers 2

21

In swift you can encapsulate variables in a struct and you can access them anywhere.

struct GlobalVariables {
    static var globalString = "MyString"
}

To call it

// Get value
let str = GlobalVariables.globalString

// Set value
GlobalVariables.globalString = "New value"

Checkout the reference for more information.

Sign up to request clarification or add additional context in comments.

2 Comments

I can't upvote you yet, but this solution totally works! Thank you :)
Np, glad to help @timtamsyoyo
1

first controller: declare variable

import UIKit

class ViewController: UIViewController {  
    var test2 = 5

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

second controller call variable

class ViewController1: UIViewController {

    var myCustomViewController: ViewController = ViewController()

    override func viewDidLoad() {
        super.viewDidLoad()

        print(myCustomViewController.test2)
    } }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.