Matthijs Otterloo Matthijs Otterloo - 1 year ago 86
Swift Question

Alamofire parameters based on value

I'm posting parameters to my API with Alamofire.

I'm trying to use different parameters based on if we have a password or not.

See a part of my code below:

let parameters: [String: Any] = [:]

if (password != nil) {
let parameters: [String : Any] = [
"displayName": firstName + " " + lastName,
"firstName": firstName,
"lastName": lastName,
"password": password ?? "",
"passwordConfirmation": password ?? "",
"location": location?.json ?? [:],
"wallet": wallet?.json ?? [:],
"gender": gender.rawValue,
"avatarId": 1,
"email": email,
"authExternalAccessToken": accessToken ?? "",
]
} else {
let parameters: [String : Any] = [
"displayName": firstName + " " + lastName,
"firstName": firstName,
"lastName": lastName,
"password": password ?? "",
"passwordConfirmation": password ?? "",
"location": location?.json ?? [:],
"wallet": wallet?.json ?? [:],
"gender": gender.rawValue,
"avatarId": 1,
"email": email,
"authExternalAccessToken": accessToken ?? "",
]
}

Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: [


when I set a breakpoint behind the if/else statement it says there are 0 elements.
What am I doing wrong?
I can probably also speed this up as it takes longer to build this way.

Answer Source

In if-else block you are creating new constant parameters, so change your code like this.

let parameters: [String: Any]

if (password != nil) {
    parameters = [
        "displayName": firstName + " " + lastName,
        "firstName": firstName,
        "lastName": lastName,
        "password": password ?? "",
        "passwordConfirmation": password ?? "",
        "location": location?.json ?? [:],
        "wallet": wallet?.json ?? [:],
        "gender": gender.rawValue,
        "avatarId": 1,
        "email": email,
        "authExternalAccessToken": accessToken ?? "",
    ] as [String : Any]
} else {
    parameters = [
        "displayName": firstName + " " + lastName,
        "firstName": firstName,
        "lastName": lastName,
        "password": password ?? "",
        "passwordConfirmation": password ?? "",
        "location": location?.json ?? [:],
        "wallet": wallet?.json ?? [:],
        "gender": gender.rawValue,
        "avatarId": 1,
        "email": email,
        "authExternalAccessToken": accessToken ?? "",
    ] as [String : Any]
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download