Glenn
Glenn

Reputation: 2806

optional variable in class definition

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

Upvotes: 0

Views: 339

Answers (2)

Max
Max

Reputation: 1552

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.

Upvotes: 0

Alain T.
Alain T.

Reputation: 42133

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

  // ...
}

Upvotes: 2

Related Questions