[英]Swift Cannot use instance member within property initializer
I want to do something like this in a class, but Swift doesn't allows it: 我想在课堂上做这样的事情,但是Swift不允许这样做:
let minDelay = Float(0.05) //Like #define minDelay 0.05 in Objective-C
private var delay = minDelay
I get an error "Cannot use instance member minDelay within property initializer". 我收到一个错误“无法在属性初始化程序中使用实例成员minDelay”。 What is the best way to correct this without initializing delay var in init or something? 在不初始化init或其他变量的情况下纠正此问题的最佳方法是什么?
You could use a static variable (which means there is a single instance that belongs to the type): 您可以使用静态变量(这意味着有一个属于该类型的实例):
class MyClass {
static let minDelay: Float = 0.05
// You can write `Self.minDelay` starting in Swift 5.1
private var delay = MyClass.minDelay
}
There are a bunch of ways to approach this, but this is probably the closest to the #define
you mentioned. 有很多方法可以解决此问题,但这可能与您提到的#define
最接近。 You could also define minDelay
outside of the class entirely, but I don't think that makes sense since it is only relevant to this class. 您也可以在类之外完全定义minDelay
,但是我认为这没有意义,因为它仅与此类相关。
Swift's property initializers can't reference other properties. Swift的属性初始值设定项无法引用其他属性。
struct S {
let a = 0
let b = a // ❌
}
error: cannot use instance member
a
within property initializer; 错误:无法在属性初始化程序中使用实例成员a
; property initializers run beforeself
is available 属性初始化程序在self
可用之前运行
This is one approach to trying to prevent circular definitions like this: 这是一种尝试防止如下循环定义的方法:
struct S {
let a = b
let b = a //❓what would these values even be?
}
Some languages like Java take a more tolerant approach, by letting a member reference any members above it (ie on a line above it), forming a directed acyclic graph of interconnected member definitions. 诸如Java之类的某些语言采用了更宽容的方法,即让成员引用其上方的任何成员(即,在其上方的一行上),从而形成互连的成员定义的有向无环图 。
Swift takes a stricter approach, and bans it outright. Swift采取了更严格的方法,并彻底禁止了它。 To get around this, you can: 要解决此问题,您可以:
Move your minDelay
variable to a different place. 将您的minDelay
变量移至其他位置。
FooConstants
case-less enum). 使它成为其他类型的静态成员(例如, FooConstants
-case-less枚举)。 Make it a lazy var
, as you said 如您所说,使其成为一个lazy var
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.