All this is about wrapping any object or type (=Any) and to be able to check if types are equal later. Works fine with a class as wrapper for the type and the value. My problem is that i want to throw in an object, find its properties through reflection and to create a wrapper for each property with the (wrapped) type of that property. Problem is that the reflected properties are always of Type Any - i would need to cast to their real type (String for example).
Example will clear things up:
// Functions to check equality of Types
func unsafeGetTypeId(type: Any.Type) -> uintptr_t {
return unsafeBitCast(type, uintptr_t.self)
}
func areOfSameType(v1: Any, v2: Any) -> Bool {
return unsafeGetTypeId(reflect(v1).valueType) == unsafeGetTypeId(reflect(v2).valueType)
}
class ZType {
}
class ZTypeT<T> {
var value: Any?
init() {
}
init( value: T ) {
self.value = value
}
}
class SampleClass {
var sampleProperty : String
init( aString: String ) {
self.sampleProperty = aString
}
}
var sample = SampleClass(aString: "Hans")
var t1 = ZTypeT<String>()
var t2 = ZTypeT(value: sample.sampleProperty)
areOfSameType(t1, t2) // true
var mirror = reflect(sample)
for var index=0; index<mirror.count; ++index {
let (propertyName, childMirror) = mirror[index]
var tTestAgainst = ZTypeT<String>()
// This is obviously of type Any so it won`t be ZTypeT<String>() but ZTypeT<Any>()
var tMirrorProp = ZTypeT(value: childMirror.value)
areOfSameType(tMirrorProp, tTestAgainst) // false
// So how could i cast the value back to it`s type? This would work but it should be generic : i don`t know the type beforehand
var tMirrorPropCasted = ZTypeT(value: childMirror.value as String)
areOfSameType(tMirrorPropCasted, tTestAgainst) // false
}
As you can see all works as expected until tMirrorProp because this won't be of type String. If i cast it my check will again be true - but well i can't cast without knowing the type. Does anybody know a solution to solve this. A solution working with Swift-Classes is preferred but a solution which works with NSObject(s) is still interresting.
Aucun commentaire:
Enregistrer un commentaire