swift全局常量:不能使用另一个常量进行初始化 [英] swift global constants: cannot use another constant for initialization

查看:228
本文介绍了swift全局常量:不能使用另一个常量进行初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我要做的事情:

class ViewController: UIViewController {
let screenRect: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenRect.width;
let screenHeight = screenRect.height;
let screenX = screenRect.origin.x
let screenY = screenRect.origin.y
override func viewDidLoad() {
...and so on

Swift允许我声明 screenRect

Swift allows me to declare screenRect.

但是,它不允许我使用它来声明任何其他常量。它向我显示错误:'ViewController.Type'没有名为'screenRect'的成员

However, it does not allow me to declare any other constants using this. It shows me the error: 'ViewController.Type' does not have a member named 'screenRect'

怎么做我定义了这些常量,为什么swift不允许我使用另一个const来定义它们。

How do I define these constants and why does not swift allow me to use another constnt to define them.

推荐答案

这些结果不知道其他全球性的因果,因为它们此时尚未初始化。你可以做的是使用计算属性:

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 }
}

这仅适用于vars,因为它的性质。应根据用例考虑这一点。如果你经常打电话,它可能不是最明智的表现方式。

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.

这篇关于swift全局常量:不能使用另一个常量进行初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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