如何根据特定模型的值构建字典数组

How to build an array of dictionaries depending on the values of a certain model

我有一个类型别名[String:Any]

public typealias Parameters = [String:Any]

我有一个计算的 属性,它将根据模型值构建这些参数。

var parameters: Parameters {
    switch self {
    case .addOFFProduct(let product):
        var parameters: Parameters!
        let code = product.code!
        let username = product.username
        let password = product.password
        if let productName = product.productName, let genericName = product.genericName, let countriesText = product.countriesText, let brandsText = product.brandsText, let storesText = product.storesText, let ingredientText = product.ingredientText, let quantity = product.quantity, let additivesText = product.additivesText, let categoriesText = product.categoriesText {
            parameters = [
                Constants.OffProduct.code:        code,
                Constants.username:               username,
                Constants.password:               password,
                Constants.OffProduct.productName: productName,
                Constants.OffProduct.genericName: genericName
            ]
        }
        return parameters
    }
}

现在我需要根据生产值构建参数类型,如果它们为零,则不会添加到 [String:Any] 中。 例如,如果 generic namenil 而其他所有不是,那么参数将如下所示

parameters = [
    Constants.OffProduct.code:        code,
    Constants.username:               username,
    Constants.password:               password,
    Constants.OffProduct.productName: productName
    //GENERIC NAME REMOVED
]

我怎样才能实现这样的逻辑。我很困惑。谢谢

对每个项目都这样做

if genericName != nil {
    parameters.updateValue(genericName,forKey:Constants.OffProduct.genericName)
}

//

创建 2 个数组,一个用于常量,另一个用于我为 nil 的值

let arrValues = [product.genericName, product.productName,,,,,,,,]
let keysArr = [Constants.OffProduct.genericName, Constants.OffProduct.productName,,,,,,,]

(0..<arrValues.count).forEach {

    if let value = arrValues[[=11=]] {

      parameters[keysArr[[=11=]]] = value 

    }

}