Obter rawValue de enum em uma função genérica
Atualização 28/8/2015: Isso será resolvido no Swift 2
VejoResposta do Twitter do desenvolvedor do compilador Swift
Atualização 10/23/2015: Com os genéricos do Swift 2, você ainda não pode obter o valor bruto. Você pode obter o valor associado.
Pergunta original:
eu tenho algunscódigo de reflexão genérico escrito rapidamente. Nesse código, estou tendo problemas para obter o valor para propriedades baseadas em uma enumeração. O problema se resume ao fato de eu não ser capaz de executar o.rawValue
no valor da propriedade que é do tipoAny
. O código de reflexão Swift retornará o valor da enumeração como tipoAny
. Então, como posso passar de um Any para um AnyObject, que é o rawValue da enumeração.
A única solução alternativa que encontrei até agora é estender todos os enum's com um protocolo. Abaixo, você pode ver um teste de unidade que é bom usando esta solução alternativa.
Existe alguma maneira de resolver isso sem adicionar código ao enum original?
para o meu código de reflexão eu preciso dogetRawValue
assinatura de método para permanecer como está.
class WorkaroundsTests: XCTestCase {
func testEnumToRaw() {
let test1 = getRawValue(MyEnumOne.OK)
XCTAssertTrue(test1 == "OK", "Could nog get the rawvalue using a generic function")
let test2 = getRawValue(MyEnumTwo.OK)
XCTAssertTrue(test2 == "1", "Could nog get the rawvalue using a generic function")
let test3 = getRawValue(MyEnumThree.OK)
XCTAssertTrue(test3 == "1", "Could nog get the rawvalue using a generic function")
}
enum MyEnumOne: String, EVRawString {
case NotOK = "NotOK"
case OK = "OK"
}
enum MyEnumTwo: Int, EVRawInt {
case NotOK = 0
case OK = 1
}
enum MyEnumThree: Int64, EVRaw {
case NotOK = 0
case OK = 1
var anyRawValue: AnyObject { get { return String(self.rawValue) }}
}
func getRawValue(theEnum: Any) -> String {
// What can we get using reflection:
let mirror = reflect(theEnum)
if mirror.disposition == .Aggregate {
print("Disposition is .Aggregate\n")
// OK, and now?
// Thees do not complile:
//return enumRawValue(rawValue: theEnum)
//return enumRawValue2(theEnum )
if let value = theEnum as? EVRawString {
return value.rawValue
}
if let value = theEnum as? EVRawInt {
return String(value.rawValue)
}
}
var valueType:Any.Type = mirror.valueType
print("valueType = \(valueType)\n")
// No help from these:
//var value = mirror.value --> is just theEnum itself
//var objectIdentifier = mirror.objectIdentifier --> nil
//var count = mirror.count --> 0
//var summary:String = mirror.summary --> "(Enum Value)"
//var quickLookObject = mirror.quickLookObject --> nil
let toString:String = "\(theEnum)"
print("\(toString)\n")
return toString
}
func enumRawValue<E: RawRepresentable>(rawValue: E.RawValue) -> String {
let value = E(rawValue: rawValue)?.rawValue
return "\(value)"
}
func enumRawValue2<T:RawRepresentable>(rawValue: T) -> String {
return "\(rawValue.rawValue)"
}
}
public protocol EVRawInt {
var rawValue: Int { get }
}
public protocol EVRawString {
var rawValue: String { get }
}
public protocol EVRaw {
var anyRawValue: AnyObject { get }
}