问题描述
设置
我已经尝试将此问题归结为最简单的形式, Xcode Version 6.1.1(6A2008a)
在 MyEnum.swift中定义的枚举
:
内部枚举MyEnum:Int {
case Zero = 0,One,Two
}
extension MyEnum {
init?(string:String){
switch string.lowercaseString {
casezero:self = .Zero
caseone:self = .One
casetwo:self = .Two
default:return nil
}
}
}
和代码,用于初始化另一个文件中的枚举, MyClass.swift
:
内部类MyClass {
let foo = MyEnum(rawValue:0)//错误
让fooStr = MyEnum(string:zero)
func testFunc(){
let bar = MyEnum(rawValue:1)//错误
let barStr = MyEnum(string:one)
}
错误
Xcode尝试使用其原始值初始化器初始化 MyEnum
时,会出现以下错误:
无法将表达式的类型(rawValue:IntegerLiteralConvertible)转换为MyEnum?
注意
-
Per :
-
MyEnum
的自定义初始值设定在扩展中定义,以测试枚举的原始值初始化程序是否被删除,因为以下情况从。但是,它实现了相同的错误结果。 The custom initializer for
MyEnum
was defined in an extension to test whether the enum's raw-value initializer was being removed because of the following case from the Language Guide. However, it achieves the same error result.Moving the enum definition to
MyClass.swift
resolves the error forbar
but not forfoo
.Removing the custom initializer resolves both errors.
One workaround is to include the following function in the enum definition and use it in place of the provided raw-value initializer. So it seems as if adding a custom initializer has a similar effect to marking the raw-value initializer
private
.init?(raw: Int) { self.init(rawValue: raw) }
Explicitly declaring protocol conformance to
RawRepresentable
inMyClass.swift
resolves the inline error forbar
, but results in a linker error about duplicate symbols (because raw-value type enums implicitly conform toRawRepresentable
).extension MyEnum: RawRepresentable {}
Can anyone provide a little more insight into what's going on here? Why isn't the raw-value initializer accessible?
This bug is solved in Xcode 7 and Swift 2
这篇关于具有自定义初始化器的Swift枚举将丢失rawValue初始化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!