swift - 如何要求在 Swift 协议(protocol)中定义枚举

标签 swift protocols

是否可以让协议(protocol)要求定义一个枚举?

//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
    }
}

最佳答案

协议(protocol)可以有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(.bar)

编辑 associatedtype 必须遵守

关于swift - 如何要求在 Swift 协议(protocol)中定义枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37353484/

相关文章:

ios - 如何使用 Base internationalizations swift 3 在运行时本身更改 ios 应用程序的语言?

ios - 在真实设备上获取位置不起作用

swift - 无法将协议(protocol)传递给具有受约束泛型类型的函数

swift - 关闭 ViewController 并调用 viewDidLoad 后 ScrollView 不会重新加载

swift - 检查是否符合 Swift 中关联类型的协议(protocol)

ios - 动态添加内容到 UIScrollView

iOS : adding zposition and button action doesn't work anymore

swift - 我可以避免子类化 NSObject 以重复调用方法吗?

objective-c - 如何在适用于 iOS 的新版 XCode 6.0.1 (6A317) 中创建 Objective-C 协议(protocol)

swift - 如何在协议(protocol)扩展中设置委托(delegate)