Can not access to singleton property in swift - 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.

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

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!

Realm Swift Results get object at index

I couldn't find this anywhere so I thought I'd ask here.
I'm using Realm in Swift and I'm having trouble to get an object out of the Results at a certain index. I'm using it inside my UITableViewController. I'm making a var at the beginning of the class:
var tasks:Results<Task>?
And then to get it I .objects(type: T.Type):
tasks = realm.objects(Task)
I was hoping to be able to do something like this:
let task = tasks!.objectAtIndex(1)
Is this a limitation or is there another way to do this?
Use standard indexing syntax to retrieve the value:
let task = tasks![1]
Since tasks is an optional, it could be nil. A safer way to write this would be to use optional binding with optional chaining:
if let task = tasks?[1] {
// use task
}

Global Variable in 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.