数组 – SWIFT – 如何获取数组的类型?
我正在编写一个通用方法,它在参数中使用Dictionary和给定类型来构建对象.
例如,如果您发出一个SOAP请求来获取一部电影,并在Dictionary中收回响应,您可以: var movie : Movie = myGenericMethod(dic : Dictionary,objectToIntrospect : Movie()) as Movie 它适用于: >简单对象 但是如果你有一个对象数组我有一个问题. 通过反射,我得到了我班级所有类型的属性. //All type of attributes of my movie object,at index [i] i have my "Actor" object var anyType : Any = typesOfProperties[i] //I cast it in object var objectType : NSObject = anyType as NSObject //Dont worry about this method,it's just for get the dictionary var otherDico : NSDictionary = ConverterUtilities.extractDictionaryFromOtherDictionary(dict,dicoName: property,soapAction: soapAction) as NSDictionary //I build the Actor object with the data of the dictionary. objectType.self give the Actor type var propertyObject: NSObject = self.buildAnyObjectWithDictionary(otherDico,soapAction: "",objectToIntrospect:objectType.self) as NSObject //I set the property Actor in my Movie object (myObjectToReturn)... The "property" parameter is the key ConverterUtilities.setPropertyValue(property,value: propertyObject,objectToReturn : myObjectToReturn,isObject : true) 它的工作完美……如果我的电影对象中只有一个actor,那么“propertyObject”将是一个Actor类型,这个原因是objectType是一个Actor对象. 但是,如果我有一个数组,我重定向处理Array的方法,我的objectType返回“Swift._NSSwiftArrayImpl”,我的anyType对象返回“([myproject.Actor])”. 这就是我现在所拥有的: var objToAdd: NSObject = self.buildAnyObjectWithDictionary(newDic,objectToIntrospect: Actor()) as NSObject arraySpecific.append(objToAdd) 正如您所看到的,如果我对类型进行硬编码,这项工作就完美无缺.但我需要像前面的例子一样!像那样: var objToAdd: NSObject = self.buildAnyObjectWithDictionary(newDic,objectToIntrospect: anObjectWithActorType) as NSObject arraySpecific.append(objToAdd) (第一个和第二个版本之间的差异是objectToIntrospect参数) 你知道我如何使用我的Any对象(包含:([myproject.Actor])来构建一个Actor的实例吗? 我真的需要你的帮助!问候 ! PS:抱歉我的英语不好,我希望你能理解我:) 解决方法
好的,我回到我的帖子,因为我找到了一个解决方案:
我创建了一个大师班,我的所有班级都是这门班的. 这个超类的方法名称为getArrayType. 如果我的一个child-class需要与我的泛型方法一起使用,并且如果她包含一个Array,则需要覆盖getArrayType. 像那样: override func getArrayType(anyType : Any) -> String { var className = " " if(anyType as? NSObject == rows){ className = Properties.PROJECT_NAME + ".SimpleRow" } return className } 我这样称呼这个方法(TObject是我的超类): var className = (objectToIntrospect as TObject).getArrayType(anyType) var obj: AnyClass! = NSClassFromString(className) 这工作完美,但您需要覆盖一个方法.如果你遇到同样的问题,我希望这有助于你! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |