Search code examples
swiftgeneric-function

avoid repeating code in swift 4


I would like to create a generic function to avoid repeating while using conditions. Is there any possible ideas to achieve this? Thanks

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
}

Solution

  • You could use keypaths

    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
    }
    

    You could go a step further and use a dictionary to lookup the keys, so in the end you would only have to pass in the keypath.