看看这个简单的协议
protocol FooOwner {
static var foo: Self { get }
}
我希望枚举符合上述协议,并且我认为这应该可行,因为静态语法SomeTypeConformingToFooOwner.foo
会导致SomeTypeConformingToFooOwner
的实例,并且在{{ 1}}是一个枚举。
SomeTypeConformingToFooOwner
解决方法是这个丑陋的事情:
enum Foo: FooOwner { // Type 'Foo' does not conform to protocol FooOwner
case foo
}
您是否有更好的解决方法来使枚举符合带有静态var的协议?
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
}
}
类似的类型。
当然可以,我可以使用一个共享的Error枚举,但是我希望每种类型都有一个特定的枚举。