如何在Swift协议中定义枚举

ufj5ltwl  于 2023-05-21  发布在  Swift
关注(0)|答案(2)|浏览(169)

有没有可能让一个协议要求定义一个枚举?

//trying to do this
protocol JSONEncodable {
    enum PropertyName // Type not allowed here
    func valueForProperty(propertyName:PropertyName) -> Any
}

//which would be implemented like this
struct Person : JSONEncodable {
    var firstName : String
    var lastName : String

    enum PropertyName {
        case FirstName
        case LastName
        func allValues() {
            return [Person.PropertyName.FirstName, Person.PropertyName.LastName]
        }
        func stringValue() {
            return "\(self)"
        }
    }
    func valueForProperty(propertyName:PropertyName) -> Any {
        switch propertyName {

        case .FirstName:
            return firstName

        case .LastName:
            return lastName
        }
    }
}

//so that I could do something like this
extension JSONEncodable {

    func JSONObject() -> [String:AnyObject] {
        var dictionary = [String:AnyObject]()
        for propertyName in PropertyName.allValues {
            let value = valueForProperty(propertyName)

            if let valueObject = value as? AnyObject {
                dictionary[propertyName.stringValue()] = valueObject

            }else if let valueObject = value as? JSONEncodable {
                dictionary[propertyName.stringValue()] = valueObject.JSONObject()
            }

        }
        return dictionary
    }
}
wlzqhblo

wlzqhblo1#

协议可以有associatedtypes,它只需要在任何子类中遵守:

enum MyEnum: String {
    case foo
    case bar
}

protocol RequiresEnum {
    associatedtype SomeEnumType: RawRepresentable where SomeEnumType.RawValue: StringProtocol

    func doSomethingWithEnum(someEnumType: SomeEnumType)
}

class MyRequiresEnum: RequiresEnum {
    typealias SomeEnumType = MyEnum

    func doSomethingWithEnum(someEnumType: SomeEnumType) {
        switch someEnumType {
        case .foo:
            print("foo")
        case .bar:
            print("bar")
        }
    }
}

let mre = MyRequiresEnum()
mre.doSomethingWithEnum(someEnumType: .bar)

编辑:associatedtype必须遵守

nvbavucw

nvbavucw2#

我认为您可以使用一个与RawRepresentable兼容的associatedtype来实现
下面是一个例子:

protocol SomeProtocol {
    associatedtype SomeType: RawRepresentable
}

如果你需要指定RawRepresentable的类型,比如String,你可以这样做:

protocol SomeProtocol {
    associatedtype SomeType: RawRepresentable where SomeType.RawValue: StringProtocol
}

现在,如果您尝试使用enum以外的任何东西来实现该协议,而不是将String作为RawRepresentable,则会出现编译器错误。希望能帮上忙。

相关问题