joels joels - 6 months ago 11
Swift Question

How to require an enum be defined in Swift Protocol

Is it possible to have a Protocol require that an enum be defined?

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

Answer

This isn't possible in Swift. If it were possible, it's unclear how you would use it directly, since you wouldn't be able to refer to any of the cases (since you don't know what they are). You'd have to as cast eventually, which breaks the whole point of the protocol. (One might imagine uses if enum were a collection type, but it's not, and if it were you could just require "a collection type.")

Comments