swift2 - Swift 2.0 Reflection for Type Analysis -
i trying analyze type information in swift 2.0 - , store in static structure - stuck. promising approach create mirror instance - done once on demand, assuming default init - , @ subjecttype of mirror elements.
my questions are:
- how unwrap optional types ( e.g.
optional<string>
). havestring
part type. - how determine generic array types, e.g.
array<foo>
.
parsing string silly , it's not possible..
other questions related arrays: if have element type, how create new instance?
to make clearer. need type information higher level algorithms such mappers - object mappers, json mappers, widget mappers, etc. - require information on type of involved objects trying type safe or inserting appropriate conversions, if needed.
think of property int
needs mapped int?
property should not raise exception.
the code far fills beandescriptor
class contains array of propertydescriptor
's should store required information
something like:
class propertydescriptor { // instance data var bean: beandescriptor; var name: string; var type: any.type; var optional = false // more data arrays, e.g. elementtype... ... }
code far analyze class is:
// create default instance let instance = create(); // need nsobject though! darn... let mirror = mirror(reflecting: instance) if let displaystyle = mirror.displaystyle { if displaystyle == .class { case let (label?, value) in mirror.children { let property = analyzeproperty(label, value: value) properties[property.name] = property; } // } }
and called function
func analyzeproperty(name : string, value: any) -> propertydescriptor { let mirror : mirror = mirror(reflecting: value) var type = mirror.subjecttype var optional = false // no way..this sucks! if (type == string?.self) { type = string.self // uhhhh optional = true } else if ... // lots other literal types, ... return propertydescriptor(bean: self, name: name, type: type, optional: optional) }
but not cover other optional classes money?
other information respect arrays, e.g. array<money>
, or array<money?>
detect array type , have determine element type
if understand question correctly want analyse class , find type of each property? had same need , got working.
i have solution finds name , type of property given class inherits nsobject
.
i wrote lengthy explanation on stackoverflow here, , project available here on github,
in short can (but check out code github):
public class func gettypesofproperties(inclass clazz: nsobject.type) -> dictionary<string, any>? { var count = uint32() guard let properties = class_copypropertylist(clazz, &count) else { return nil } var types: dictionary<string, any> = [:] in 0..<int(count) { guard let property: objc_property_t = properties[i], let name = getnameof(property: property) else { continue } let type = gettypeof(property: property) types[name] = type } free(properties) return types }
Comments
Post a Comment