有自定义初始化器的Swift枚举将丢失rawValue初始化程序

有自定义初始化器的Swift枚举将丢失rawValue初始化程序

本文介绍了具有自定义初始化器的Swift枚举将丢失rawValue初始化程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!



设置



我已经尝试将此问题归结为最简单的形式, 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?



注意




  1. Per :


  2. MyEnum 的自定义初始值设定在扩展中定义,以测试枚举的原始值初始化程序是否被删除,因为以下情况从。但是,它实现了相同的错误结果。

  3. 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.

  4. Moving the enum definition to MyClass.swift resolves the error for bar but not for foo.

  5. Removing the custom initializer resolves both errors.

  6. 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)
    }
    

  7. Explicitly declaring protocol conformance to RawRepresentable in MyClass.swift resolves the inline error for bar, but results in a linker error about duplicate symbols (because raw-value type enums implicitly conform to RawRepresentable).

    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初始化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 09:56