Global Variable in Swift - swift

I'm creating an iOS 8 app and I want to create a string variable that is accessible to all class. I tried to create global.swift with a string variable in it. I can access the variable but, everytime I initialize the class again using this line let globalVar = global() the value that I've passed returns a nil value. Can someone help me with this. Thank you.

You can put the variable in your AppDelegate, which is a singleton. See this post for how to access the AppDelegate
How do I get a reference to the app delegate in Swift?

Put
public static var global = "String"
in any class. Access via Classname.global.

Just use your Global.swift file and put your global variables and functions inside without any class around it.
//
// Global.swift
//
let myConstant = 5
func myGlobalFunction() {
// ...
}
You can access those variables and functions all around your module.

Related

Whats the difference between initializing a variable within a class VS without??? - swift

Here's my problem, I have a variable that I initialize once so that I don't have to call the database every time I want to use that variable. How should I structure it? Example 1 or 2? What's the difference between putting functions and variables inside a class vs without a class?
example 1 (no class):
import UIKit
var username = ""
func callToDatbase () {
// I run my code to set the username value equal to stored username value within the database
//Ex: username = database.username
}
---------------------------------------------------------------------------------------------------------
//Then when I want to call it in another view controller I would just say:
usernameLabel.text = username
Example 2 (with class):
import UIKit
class Initializers {
var username = ""
func callToDatbase () {
// I run my code to set the username value equal to stored username value within the database
//Ex: self.username = database.username
}
}
---------------------------------------------------------------------------------------------------------
//Then when I want to call it in another view controller I would just say:
usernameLabel.text = Initializers().username
When you initialise a variable outside of the class it is store in the global scope. The scope in swift is defined by the curly brackets, so you can think about the outside of the class as the whole project surrounded by the curly brackets. When you define the variable inside of the class it is only going to be available from that class when you instantiate it as an object. You might want to read about inheritance to find out what else you can do with variables in classes.
TLDR: Variable outside will be available to the whole code, whereas the one inside the class will only be available from within the class or by accessing it as a property from instantiated object.
Example code:
class Example {
var name = "Antoni"
}
print(name) // Will throw error
let example = Example() // Create an instance of the class
print(example.name) // Prints as expected
It is preferred to put variables in some sort of instantiable/destructible structure like a class to help swift with memory management. The variables defined globally will not be removed from memory until the program exits. And if you need to store static variables use struct instead.

didSet and Getter in Swift array

I want to initialise elements only if an array has been set from outside the current class. Looks like a use for didSet!
// external API
var arr: [Display] = [] {
didSet {
array = arr
initialiseElements(arr: arr)
}
}
// internal
private var array: [Display] = []
but when we return the value from arr it might not be correct - I want to use array as a backing store.
I tried to use a getter on arr but this isn't allowed in Swift. How can I prevent the use of arr within the class, or otherwise ensure we only initiliseElements(:) via calls outside the class?
Why use didSet? why not set?
var arr: [Display] {
set {
array = newValue
initialiseElements(arr: newValue)
}
get {
return self.array
}
}
How can I prevent the use of arr within the class?
You can't, swift doesn't have such access control
otherwise ensure we only initiliseElements(:) via calls outside the class
Again, you can't.
It makes no sense logically as well, think of what you are asking for, you are asking class to declare a variable which itself cant set (read only) but should expose to it outside class to write (read + write) it?
How is that possible? What is the use case you are trying to solve here? If for some reason you ended up with this solution, may be solutioning is wrong! re think of your implementation.
Hope this helps

Can not access to singleton property in swift

I'm trying to create singleton and use it.
But when I try to access to its propery, it shows me error.
How can I fix it?
or
Use
class Test {
let sharedManager: Manager = {
var shared = Manager.shared
shared.str = "update"
return shared
}()
}
You cannot just put statements like print or assignments wherever you want. Generally, they will be inside functions/closures. In my example, I am using a closure to get the Manager and initialize it -- the () at the end of it calls the closure to cause it to run.

Global 'let' declaration requires an initializer expression

I am working on iOS code with Xcode 10.2.1.
I have an issue when declaring a let global variable:
import UIKit
import CouchbaseLiteSwift
private let database: Database
This gives the compiler error below:
Global 'let' declaration requires an initializer expression
I don't know how to make database a global variable in this case. I searched about it, but all says about some int or string initialization but not when initializing classes like Database. Because, Couchbase's Database class is a big class. I can't do it with "= null"
Any help please?
You need a variable if you're not sure what it is so that later you can change it:
private var database: Database?
There's no point in defining a constant if you're not going to actually define it as something.
The distinguishing feature of a let variable is that it is assigned to exactly once before being read.
When a let declaration is a local variable, Swift can analyze the code to make sure that the variable will be initialized exactly once before it is used. This is why you can declare a local let variable with no initial value. For example:
let greeting: String
if(light.isOn()) {
greeting = "Hello!"
} else {
greeting = "Who’s there?!"
}
// Now it is OK to use greeting, because we _know_ the code took
// exactly one branch of the if, and each branch initializes greeting
print(greeting) // OK
With an instance variable, you don't need to specify an initial value as long as every initializer sets it exactly once.
However, with a global variable, the compiler can't really make any guarantees about who will assign to it when. You therefore have to give it an initial value right on the spot.
As #rmaddy points out in the comments, it might look like this:
private let database = Database(name: "foo")
If initialization takes multiple statements, you can batch them up in a closure like this:
private let database = {
let config = readConfigFile()
guard let dbName = config["database"] else {
fatalError("Missing config for 'database'")
}
return Database(name: dbName)
}()
If you must make it a global, but it just isn't possible to initialize it until later, you must make it a var:
private var database: Database?
…or if you want any attempt to use it before it’s initialized to be a crasher:
private var database: Database!

How to create a global variable?

I have a global variable that needs to be shared among my ViewControllers.
In Objective-C, I can define a static variable, but I can't find a way to define a global variable in Swift.
Do you know of a way to do it?
From the official Swift programming guide:
Global variables are variables that are defined outside of any
function, method, closure, or type context. Global constants and
variables are always computed lazily.
You can define it in any file and can access it in current module anywhere.
So you can define it somewhere in the file outside of any scope. There is no need for static and all global variables are computed lazily.
var yourVariable = "someString"
You can access this from anywhere in the current module.
However you should avoid this as Global variables are not good for application state and mainly reason of bugs.
As shown in this answer, in Swift you can encapsulate them in struct and can access anywhere.
You can define static variables or constant in Swift also. Encapsulate in struct
struct MyVariables {
static var yourVariable = "someString"
}
You can use this variable in any class or anywhere
let string = MyVariables.yourVariable
println("Global variable:\(string)")
//Changing value of it
MyVariables.yourVariable = "anotherString"
Global variables that are defined outside of any method or closure can be scope restricted by using the private keyword.
import UIKit
// MARK: Local Constants
private let changeSegueId = "MasterToChange"
private let bookSegueId = "MasterToBook"
if you want to use it in all of your classes you can use:
public var yourVariable = "something"
if you want to use just in one class you can use :
var yourVariable = "something"
If you don't actually want a global variable, but instead want to save values that persist even when the app closes you can do this:
If you don't actually want to pass data between view controllers but rather simply want to store a global variable you can do this:
This gives a great explanation for how to do this in Swift 5: https://www.hackingwithswift.com/example-code/system/how-to-save-user-settings-using-userdefaults
Summary:
To set a value:
let defaults = UserDefaults.standard
defaults.set("value", forKey: "key")
To get a String value:
let key = defaults.object(forKey: "StringKey") as? [String] ?? [String]()
To get integer value:
let key = defaults.integer(forKey: "IntegerKey")