问题
optionals in class definition
I have a 'mastermodel' from which most of my models inherit so they can have the configuration constants
class MasterModel {
static let apiKey = (drop.config["app","thinx-api-key"]?.string)!
static let baseURL = (drop.config["app","base-URL"]?.string )!
}
Notice the force unwraps :( In this case it's not really a huge problem as the program won't start without these constants but I'd like to clean this up anyway.
guard statements are only allowed in functions, not in the class definition. What is the proper way to define those constants with error trapping
回答1:
You could assign them with a computed closure to detect the configuration error
class MasterModel
{
static let apiKey:String = {
if let result = drop.config["app","thinx-api-key"]?.string
{ return result }
print("MasterModel.apiKey error, missing app/thinx-api-key")
return ""
}() // the () here makes the closure execute and return the value
// ...
}
回答2:
If you like your program to crash only if you actually use the property, you could use a computed/lazy one:
class MasterModel {
static var apiKey: String {
get {
return drop.config["app","thinx-api-key"]?.string)!
}
}
...
}
This might be useful in case the static initialiser is called before drop has been successfully initialised.
来源:https://stackoverflow.com/questions/43683509/optional-variable-in-class-definition