简体   繁体   English

快速宣言的问题

[英]Problems with Swift Declaration

I just ask myself why I can't do something like this directly under my Class Declaration in Swift: 我只是问自己为什么我不能直接在Swift的Class声明中做这样的事情:

let width = 200.0
let height = 30.0

let widthheight = width-height

I can not create a constant with 2 other constants. 我不能用2个其他常量创建常量。 If I use this inside a function/method everything works fine. 如果我在函数/方法中使用它一切正常。

Thanks 谢谢

When you write let widthheight = width - height , this implicitly means let widthheight = self.width - self.height . 当你写下let widthheight = width - height ,这隐含意味着let widthheight = self.width - self.height let widthheight = width - height let widthheight = self.width - self.height In Swift, you're simply not allowed to use self until all its members have been initialised — here, including widthheight . 在Swift中,只有在所有成员都被初始化之后才允许使用self - 这里包括widthheight

You have a little bit more flexibility in an init method, though, where you can write things like this: 但是,在init方法中你有一点灵活性,你可以在这里写下这样的东西:

class Rect {

    let width = 200.0
    let height = 30.0
    let widthheight: Double
    let widthheightInverse: Double

    init() {
        // widthheightInverse = 1.0 / widthheight // widthheight not usable yet
        widthheight = width - height
        widthheightInverse = 1.0 / widthheight // works
    }

}

This is a candidate for a computed property as such: 这是计算属性的候选者:

class Foo {
  let width = 200.0
  let height = 30.0
  var widthheight : Double { return width - height }
}

You might raise an issue of 'but it is computed each time'; 您可能会提出一个问题'但它每次计算'; perhaps your application will depend on a single subtraction done repeatedly - but not likely. 也许你的应用程序将依赖于重复进行的单个减法 - 但不太可能。 If the subtraction is an issue, set widthheight in init() 如果减法是个问题,请在init()设置widthheight

For things like that, you could make use of class variables. 对于类似的东西,你可以使用类变量。 The code would look like this: 代码如下所示:

class var width = 200.0
class var height = 30.0
class var widthheight = width - height

But when you try it, you will see a compiler error: 但是当你尝试它时,你会看到编译器错误:

Class variables are not yet supported 尚不支持类变量

I guess they haven't implemented that feature yet. 我猜他们还没有实现这个功能。 But there is a solution for now. 但是现在有一个解决方案。 Just move your declarations outside the class declaration, like following: 只需将声明移到类声明之外,如下所示:

let width = 200.0
let height = 30.0
let widthheight = width - height

class YourClass { ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM