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

时间:2018-09-22 15:49:27

标签: swift model url-parameters type-alias

我的类型别名为[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
    }
}

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

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

如何实现这样的逻辑。我很困惑。谢谢

1 个答案:

答案 0 :(得分:1)

对每个项目都这样

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[$0] {

      parameters[keysArr[$0]] = value 

    }

}