【问题标题】:Swift: Protocol `static var foo: Self` and enumsSwift:协议`static var foo:Self`和枚举
【发布时间】:2019-02-19 15:37:48
【问题描述】:

简化示例

看看这个简单的协议

protocol FooOwner {
    static var foo: Self { get }
}

我希望枚举符合所述协议,并且在我看来这应该可行,因为静态语法 SomeTypeConformingToFooOwner.foo 应该导致 SomeTypeConformingToFooOwner 的实例,并且在 SomeTypeConformingToFooOwner 是枚举的情况下.

enum Foo: FooOwner { // Type 'Foo' does not conform to protocol FooOwner
    case foo
}

解决方法就是这个丑陋的东西:

protocol FooOwner {
    static var fooOwner: Self { get }
}

enum Foo: FooOwner {
    case foo
    static var fooOwner: Foo {
        return Foo.foo
    }
}

对于符合静态变量协议的枚举,您有更好的解决方法吗?

实际用例

protocol StringConvertibleError: Swift.Error {
    static var invalidCharactersError: Self { get }
}

protocol StringConvertibleErrorOwner {
    associatedtype Error: StringConvertibleError
}

protocol StringConvertible {
    var value: String { get }

    /// Calling this with an invalid String will result in runtime crash.
    init(validated: String)

    init(string value: String) throws

    static func validate(_ string: String) throws -> String
}

// MARK: - Default Implementation Constrained
extension StringConvertible where Self: CharacterSetSpecifying, Self: StringConvertibleErrorOwner {
    static func validate(_ string: String) throws -> String {
        guard Self.allowedCharacters.isSuperset(of: CharacterSet(charactersIn: string)) else {
            throw Error.invalidCharactersError
        }
        // Valid
        return string
    }
}

struct HexString: StringConvertible, CharacterSetSpecifying, StringConvertibleErrorOwner {

    static var allowedCharacters = CharacterSet.hexadecimal

    let value: String

    init(validated unvalidated: String) {
        do {
            self.value = try HexString.validate(unvalidated)
        } catch {
            fatalError("Passed unvalid string, error: \(error)")
        }
    }
}

extension HexString {
    enum Error: StringConvertibleError {
        static var invalidCharactersError: Error {
            return Error.invalidCharacters
        }

        case invalidCharacters
    }
}

所以这是我要更改的最后一部分:

extension HexString {
    enum Error: StringConvertibleError {
        case invalidCharacters
    }
}

因为我有很多与HexString相似的类型。

是的,当然我可以使用一个共享的错误枚举,但我希望每种类型都有一个特定的枚举。

【问题讨论】:

  • static var foo != case foo
  • 解决方法不错,假设您使用适当的名称。您想用这种方法解决什么问题吗?也许我们可以找到替代方案。
  • @tikhonov-alexander 嗯,是的,我知道......但如果 Swift 可以支持通过一些常见的 case 将不同的枚举桥接在一起,那就太好了。是的,当然,我可以使用open enum(例如struct),但我真的很想使用枚举。

标签: swift enums swift-protocols


【解决方案1】:

SE-0280 解决了这个问题 - 如果被接受。目前正在审核中。

编辑 1

好消息,SE-0280 has been accepted

【讨论】:

    猜你喜欢
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-23
    • 2014-11-09
    • 1970-01-01
    • 2015-01-29
    相关资源
    最近更新 更多