【发布时间】:2023-03-13 17:30:01
【问题描述】:
所有这些都是关于包装任何对象或类型 (=Any) 并能够在以后检查类型是否相等。使用类作为类型和值的包装器可以正常工作。我的问题是我想抛出一个对象,通过反射找到它的属性,并为每个属性创建一个包装器,并使用该属性的(包装)类型。问题是反射属性总是类型 Any - 我需要转换为它们的真实类型(例如字符串)。
示例将解决问题:
// 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
}
正如您所见,在 tMirrorProp 之前所有工作都按预期工作,因为这不是字符串类型。如果我施放它,我的检查将再次为真 - 但是我不能在不知道类型的情况下施放。有谁知道解决这个问题的解决方案。首选使用 Swift-Classes 的解决方案,但使用 NSObject(s) 的解决方案仍然很有趣。
【问题讨论】:
-
也许这段代码可以提供帮助。它能够将对象向后解析并转发到字典。 github.com/evermeer/EVCloudKitDao/blob/master/AppMessage/…
标签: swift reflection generics