My problem is that I need to get this specific variable to be initialized no matter what, because there's another object that depends on this variable's value
Here's the code (I set the variable as global)
lazy var getToken = {
if let token = keychain["token"].string {
return token
}
}()
I'm using lazy because I need this to get initialized no matter what.
I got this error error When I trying to put it on a global file
'lazy' may not be used on an already-lazy global
Here's the object that is depending on this token
Singleton Design
class SocketIOManager: NSObject {
static let sharedInstance = SocketIOManager()
let socket: SocketIOClient!
private override init() {
super.init()
socket = SocketIOClient(socketURL: URL(string: mainURL)!, .connectParams(["token": getToken])])
}
}
If you take a look at socket =
at "token"
, that's where I need the token
IMPORTANT
user2908517's answer is totally wrong. so request to read this once.
According to docs https://docs.swift.org/swift-book/LanguageGuide/Properties.html
Global constants and variables are always computed lazily, in a similar manner to Lazy Stored Properties. Unlike lazy stored properties, global constants and variables do not need to be marked with the lazy modifier.
Local constants and variables are never computed lazily.
Which means Global constants and variables not class properties they are both different just like the ocean and river. Request to read https://stackoverflow.com/a/33837338/4601900
Class properties are not lazy by default, class property automatically init when it's init method called either designated or convenience.
I don't understand why you are putting lazy over there ?
Lazy can be used when you want to initialize a variable when they actually needed by compiller .
Other then lazy type (normal var) will be initialize as soon as designated initializer called
You can use
var getToken : String? = { if let token = keychain["token"].string { return token } }
I am not sure what you mean by "I'm using lazy because I need this to get initialized no matter what.", but all global variables are lazy by default, that is why no need (and not allowed) to place keyword "lazy" before the global variable declaration: they are already lazy by their nature.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With