继承下的结构静态变量
Struct static vars under inheritance
在这种情况下如何解决歧义,前提是我不能为每个 class 更改名称 Static
和名称 SOMECONST
(以保持一致的约定) API classes)
它可能会或可能不会在操场上工作,但错误 AMBIGUOUS USE OF SOMECONST
出现在 Xcode 的编译过程中。
如果不可能,那么我将恢复为 getter,任何人都知道 Apple 是否会为 classes 实施 static
,或者它仅为 struct
设计和 enum
???
public class A {
public struct Static {
public static let SOMECONST = 1
}
init(val: Int) {
println(val)
}
}
public class B: A {
public struct Static {
public static let SOMECONST = 2
}
init() {
super.init(val: B.Static.SOMECONST)
}
}
B()
该程序(不出所料)无法编译,因为它找到了 SOMECONST
符号的两个候选者:
error: ambiguous use of 'SOMECONST'
super.init(val: B.Static.SOMECONST)
^
note: found this candidate
static let SOMECONST = 2
^
note: found this candidate
static let SOMECONST = 1
^
像这样使用嵌套类型来存储常量通常不是一个好主意,因为嵌套类型不能被 subclasses 覆盖。您应该直接将常量声明为 class.
的一部分
现在,理想情况下你会做这样的事情:
class A {
class let SOMECONST = 1
}
class B: A {
override class let SOMECONST = 2
}
但是,不幸的是,当前的 Swift 编译器不支持此功能。覆盖 class(静态)变量的唯一方法是使其可计算:
class A {
class var SOMECONST: Int {
return 1
}
}
class B: A {
override class var SOMECONST: Int {
return 2
}
}
这有点丑陋,但它确实有效。您现在可以创建 B
的初始值设定项:
init() {
super.init(val: B.SOMECONST) // prints "2"
}
在这种情况下如何解决歧义,前提是我不能为每个 class 更改名称 Static
和名称 SOMECONST
(以保持一致的约定) API classes)
它可能会或可能不会在操场上工作,但错误 AMBIGUOUS USE OF SOMECONST
出现在 Xcode 的编译过程中。
如果不可能,那么我将恢复为 getter,任何人都知道 Apple 是否会为 classes 实施 static
,或者它仅为 struct
设计和 enum
???
public class A {
public struct Static {
public static let SOMECONST = 1
}
init(val: Int) {
println(val)
}
}
public class B: A {
public struct Static {
public static let SOMECONST = 2
}
init() {
super.init(val: B.Static.SOMECONST)
}
}
B()
该程序(不出所料)无法编译,因为它找到了 SOMECONST
符号的两个候选者:
error: ambiguous use of 'SOMECONST'
super.init(val: B.Static.SOMECONST)
^
note: found this candidate
static let SOMECONST = 2
^
note: found this candidate
static let SOMECONST = 1
^
像这样使用嵌套类型来存储常量通常不是一个好主意,因为嵌套类型不能被 subclasses 覆盖。您应该直接将常量声明为 class.
的一部分现在,理想情况下你会做这样的事情:
class A {
class let SOMECONST = 1
}
class B: A {
override class let SOMECONST = 2
}
但是,不幸的是,当前的 Swift 编译器不支持此功能。覆盖 class(静态)变量的唯一方法是使其可计算:
class A {
class var SOMECONST: Int {
return 1
}
}
class B: A {
override class var SOMECONST: Int {
return 2
}
}
这有点丑陋,但它确实有效。您现在可以创建 B
的初始值设定项:
init() {
super.init(val: B.SOMECONST) // prints "2"
}