Junaid
Junaid

Reputation: 381

Share variables in Playground

I’ve got a public class with variables declared in a sources file. I’m trying to set these variable in page 1 (of the playground book) to use in page 2. At the moment I can see the class but it doesn’t allow me to access the variables even if I declare them as public.

Data.swift

 public class GlobalVars {
       public var progress = Float()
       public var didComplete = Bool()

}

Contents.swift

GlobalVar().progress = 1

I'd also tried this

Data.swift

 public class GlobalVars {
       public var progress:Float?
       public var didComplete;Bool?

    public init() progress:Float? = nil, didComplete:Bool? = nil {
    self.progress = progress
    self.didComplete = didComplete
    }

}

They're optionals so I can set each individually but when I set one everything else is then set to nil. If I try get a value after I set it, I still get nil.

Upvotes: 0

Views: 847

Answers (1)

Ionescu Vlad
Ionescu Vlad

Reputation: 151

Use singleton pattern in order to be able to access shared variables. Here is a code that will work in your case. Add the GlobalClass class to source

     import Foundation
   // GlobalVars.swift has to be in source files     
        public class GlobalVars {
           public var progress:Float = 0.0
           public var didComplete:Bool = true
           public static let sharedInstance = GlobalVars()
            private init() {}
        }

And in your page you can use it after like this.

import UIKit

GlobalVars.sharedInstance.progress = 1
GlobalVars.sharedInstance.didComplete = false
print(GlobalVars.sharedInstance.progress)
print(GlobalVars.sharedInstance.didComplete)

I've just tested this and it works

Upvotes: 0

Related Questions