类定义中的可选变量 [英] optional variable in class definition

查看:90
本文介绍了类定义中的可选变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类定义中的可选选项

我有一个"mastermodel",我的大多数模型都从"mastermodel"继承而来,因此它们可以具有配置常量

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语句仅允许在函数中使用,而不能在类定义中使用.用错误陷阱定义那些常量的正确方法是什么

guard statements are only allowed in functions, not in the class definition. What is the proper way to define those constants with error trapping

推荐答案

您可以为它们分配计算闭包以检测配置错误

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

  // ...
}

这篇关于类定义中的可选变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆