避免在swift 4中重复代码

时间:2018-03-06 06:56:58

标签: swift generic-function

我想创建一个通用函数,以避免在使用条件时重复。有没有可能的想法来实现这一目标? 感谢

struct ObjectDataItem {
var name: String
var value: String
}

static func arrayFields(arrayObject: ArrayObject) -> Array<ObjectDataItem> {
    var objectFields = [ObjectDataItem]()

    if let objectCategoryValue = arrayObject.objectCategory {
        let data = [ObjectDataItem(name: ObjectCategoryConstant.objectCategoryKey, value: objectCategory)]
        objectFields.append(contentsOf: data)
    }

    if let objectTypeValue = arrayObject.objectType {
        let data = [ObjectDataItem(name: ObjectTypeConstant.objectTypeKey, value: objectTypeValue)]
        objectFields.append(contentsOf: data)
    }

    if let objectName = arrayObject.objectName {
        let data = [ObjectDataItem(name: ObjectNameConstant.objectNameKey, value: objectName)]
        objectFields.append(contentsOf: data)
    }

    if let countryObjectValue = arrayObject.countryObjectCode {
        let data = [ObjectDataItem(name: countryObjectConstant.countryObjectCodeKey, value: countryObjectValue)]
        objectFields.append(contentsOf: data)
    }

    return objectFields
}

3 个答案:

答案 0 :(得分:1)

您可以使用密钥路径

func arrayFields(arrayObject: ArrayObject) -> Array<ObjectDataItem> {
    var objectFields = [ObjectDataItem]()

    func appendField(key: String, valuePath: KeyPath<ArrayObject, String?>) {
        if let value = arrayObject[keyPath: valuePath] {
            let data = [ObjectDataItem(name: key, value: value)]
            objectFields.append(contentsOf: data)
        }
    }

    appendField(key: ObjectCategoryConstant.objectCategoryKey, valuePath: \ArrayObject.objectCategory)
    appendField(key: ObjectCategoryConstant.objectTypeKey, valuePath: \ArrayObject.objectType)

    return objectFields
}

您可以更进一步,使用字典查找密钥,因此最后您只需要传入密钥路径。

答案 1 :(得分:0)

对我来说唯一有意义的是先创建一个字典:

var dataDictionary: [String: String] = [:]
dataDictionary[ObjectCategoryConstant.objectCategoryKey] = arrayObject.objectCategory
dataDictionary[ObjectCategoryConstant.objectTypeKey] = arrayObject.objectType
dataDictionary[ObjectCategoryConstant.objectNameKey] = arrayObject.objectName
dataDictionary[countryObjectConstant.countryObjectCodeKey] = arrayObject.countryObjectValue

let objectFields = dataDictionary.map { (name, value) in
    ObjectDataItem(name: name, value: countryObjectValue)
}

词典不包含nil的值。但是,您丢失了值的排序(如果它对您很重要)。简化也不是很大。

答案 2 :(得分:0)

如果您不介意将您的密钥作为您的属性名称,您也可以使用反射:像这样:

func arrayFields(arrayObject: ArrayObject) -> Array<ObjectDataItem> {
    var objectFields = [ObjectDataItem]()
    let objectMirror = Mirror(reflecting: arrayObject)
    for child in objectMirror.children {
        let (propertyName, propertyValue) = child
        objectFields.append(ObjectDataItem(name:propertyName!, value: propertyValue as! String))
    }
    return objectFields
}
相关问题