swift global constants: cannot use another constant for initialization

后端 未结 3 952
时光说笑
时光说笑 2021-01-14 20:10

Here is what I am trying to do:

class ViewController: UIViewController {
let screenRect: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenRect.w         


        
3条回答
  •  一向
    一向 (楼主)
    2021-01-14 20:41

    The consts do not know about the other global consts because they are not initialized at this point. What you could do though is to use computed properties:

    class ViewController: UIViewController {
      var screenRect: CGRect { return UIScreen.mainScreen().bounds }
      var screenWidth: CGFloat { return self.screenRect.origin.x }
    }
    

    This only works with vars, due to the nature of it. This should be considered depending on the use case. If you have to call it often, it might not be the wisest way in regards to performance.

提交回复
热议问题