看看这个简单的协议
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
相似的类型。
当然可以,我可以使用一个共享的Error枚举,但是我希望每种类型都有一个特定的枚举。
SE-0280解决了这个问题-如果被接受。目前正在审查中。