gpt4 book ai didi

带有自定义初始化器的 Swift 枚举丢失了 rawValue 初始化器

转载 作者:IT王子 更新时间:2023-10-29 04:56:55 24 4
gpt4 key购买 nike

我试图通过以下方式将这个问题归结为最简单的形式。

设置

Xcode 版本 6.1.1 (6A2008a)

MyEnum.swift 中定义的枚举:

internal enum MyEnum: Int {
case Zero = 0, One, Two
}

extension MyEnum {
init?(string: String) {
switch string.lowercaseString {
case "zero": self = .Zero
case "one": self = .One
case "two": self = .Two
default: return nil
}
}
}

以及在另一个文件 MyClass.swift 中初始化枚举的代码:

internal class MyClass {
let foo = MyEnum(rawValue: 0) // Error
let fooStr = MyEnum(string: "zero")

func testFunc() {
let bar = MyEnum(rawValue: 1) // Error
let barStr = MyEnum(string: "one")
}
}

错误

Xcode 在尝试使用其原始值初始化器初始化 MyEnum 时出现以下错误:

Cannot convert the expression's type '(rawValue: IntegerLiteralConvertible)' to type 'MyEnum?'

注意事项

  1. 根据 the Swift Language Guide :

    If you define an enumeration with a raw-value type, the enumeration automatically receives an initializer that takes a value of the raw value’s type (as a parameter called rawValue) and returns either an enumeration member or nil.

  2. MyEnum 的自定义初始值设定项在扩展中定义,以测试枚举的原始值初始值设定项是否由于来自 the Language Guide 的以下情况而被删除.但是,它实现了相同的错误结果。

    Note that if you define a custom initializer for a value type, you will no longer have access to the default initializer (or the memberwise initializer, if it is a structure) for that type. [...]
    If you want your custom value type to be initializable with the default initializer and memberwise initializer, and also with your own custom initializers, write your custom initializers in an extension rather than as part of the value type’s original implementation.

  3. 将枚举定义移动到 MyClass.swift 解决了 bar 但不是 foo 的错误。

  4. 删除自定义初始化程序可解决这两个错误。

  5. 一种解决方法是在枚举定义中包含以下函数,并用它代替提供的原始值初始值设定项。因此,似乎添加自定义初始化程序与将原始值初始化程序标记为 private 具有类似的效果。

    init?(raw: Int) {
    self.init(rawValue: raw)
    }
  6. MyClass.swift 中明确声明协议(protocol)符合 RawRepresentable 可解决 bar 的内联错误,但会导致链接器错误关于重复符号(因为原始值类型枚举隐式符合 RawRepresentable)。

    extension MyEnum: RawRepresentable {}

任何人都可以更深入地了解这里发生的事情吗?为什么原始值初始值设定项不可访问?

最佳答案

此错误已在 Xcode 7 和 Swift 2 中解决

关于带有自定义初始化器的 Swift 枚举丢失了 rawValue 初始化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27390989/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com