Swfit 3.1:Enum及其幽灵.init(rawValue :)

时间:2017-05-06 21:04:26

标签: swift enums compiler-errors

a bug report regarding this issue has been filed on swift.org

假设您已经在类之外定义了一个枚举,您希望在map函数中使用它来返回静态常量的字符串:

public enum SoundCatMakes : Int{
    case meow = 0, meoww, nyan, thrr, rawr, count
}

public class Nekko{
  static let sayHi : String = [Int](0..<SoundCatMakes.count.rawValue).map{
      String(describing: SoundCatMakes.init(rawValue: $0)!) 
  }.joined(separator: ",")
}

这完全没问题。它通过编译器没有错误。但是如果你改变枚举和类的定义顺序,编译器会抱怨枚举没有成员init

enter image description here

看起来它与Swift.RawRepresentable的初始值设定项的failable性质有关。

现在排序很重要,当我们在不同的文件中有类和枚举时,我们可以遇到真正的问题,Swift编译器只是决定在包含枚举定义的文件之前处理包含类定义的文件(这是什么我在我的项目中遇到过。)

如何解决此问题(除了在同一文件中同时使用枚举和类定义)?

有趣的事实

在这种情况下,也会遇到同样的错误:

public enum SoundCatMakes : Int{
    case meow = 0, meoww, nyan, thrr, rawr, count
}


public class Nekko{
    let sayHi = SoundCatMakes.init(rawValue: 0)! // error: type 'SoundCatMakes' has no member 'init'

}

但是当关闭类型推断时,错误消失了:

public enum SoundCatMakes : Int{
    case meow = 0, meoww, nyan, thrr, rawr, count
}


public class Nekko{
    let sayHi : SoundCatMakes = SoundCatMakes.init(rawValue: 0)! // and now the compiler is cool with this

}

然而,这个技巧对上述问题并不起作用:

public class Nekko{
    static let sayHi : String = [Int](0..<SoundCatMakes.count.rawValue).map{
        let sound : SoundCatMakes = SoundCatMakes.init(rawValue: $0)! //still got the same error..
        String(describing: sound)
        }.joined(separator: ",")
}

public enum SoundCatMakes : Int{
    case meow = 0, meoww, nyan, thrr, rawr, count
}

0 个答案:

没有答案