optional variable in class definition

試著忘記壹切 提交于 2020-01-07 04:18:07

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!