【问题标题】:SWIFT - How to get the type of an Array?SWIFT - 如何获取数组的类型?
【发布时间】:2015-05-06 22:42:53
【问题描述】:

我正在编写一个通用方法,它采用字典和给定类型的参数来构建对象。

例如,如果您发出 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)

它工作得很好......如果我的电影对象中只有一个演员,“propertyObject”将是一个演员类型,这导致 objectType 是一个演员对象。

但是,如果我有一个数组,我会在处理 Array 的方法中重定向,我的 objectType 返回“Swift._NSSwiftArrayImpl”,我的 anyType 对象返回“([myproject.Actor])”。 我不需要知道这只是一个数组,因为我知道。但我需要知道这是一个 Actor 数组,用于动态构建一些 Actor 对象!

这是我目前拥有的:

var objToAdd: NSObject = self.buildAnyObjectWithDictionary(newDic, soapAction: "", objectToIntrospect: Actor()) as NSObject

arraySpecific.append(objToAdd)

如您所见,如果我对类型进行硬编码,这将非常有效。但我需要让它像前面的例子一样!像这样:

var objToAdd: NSObject = self.buildAnyObjectWithDictionary(newDic, soapAction: "", objectToIntrospect: anObjectWithActorType) as NSObject

arraySpecific.append(objToAdd)

(第一版和第二版的区别在于objectToIntrospect参数)

你知道如何使用我的 Any 对象(包含:([myproject.Actor]) 来构建一个 Actor 的实例吗?

我真的需要你的帮助!问候!

PS:对不起我的英语不好,希望你能理解我:)

【问题讨论】:

    标签: arrays swift types generics


    【解决方案1】:

    好的,伙计们,我回到我的帖子,因为我找到了解决方案: 我创建了一个大师班,我所有的班级都继承了这个班级。

    这个超类有一个方法名getArrayType。

    如果我的一个子类需要与我的泛型方法一起使用,并且如果她包含一个数组,则他们需要覆盖 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)
    

    这很完美,但是你需要重写一个方法。如果您遇到同样的问题,我希望这对您有所帮助!

    【讨论】:

      猜你喜欢
      • 2017-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-07
      • 1970-01-01
      • 2014-11-30
      相关资源
      最近更新 更多