我正在使用Alamofire向API发布参数。
我试图根据我们是否有密码使用不同的参数。
请参阅下面的部分代码:
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: [
当我在if / else语句后面设置一个断点时,它说有0个元素。
我做错了什么?我可能也可以加快速度,因为建立这种方式需要更长的时间。
答案 0 :(得分:3)
在if-else
块中,您正在创建新常量parameters
,因此请更改此代码。
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]
}
答案 1 :(得分:1)
您正在重新声明您的参数变量,而不是分配给它。
您只能一次分配一个let变量,但该赋值不必作为与声明相同的语句的一部分发生。
例如:
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 ?? "",
]
} 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 ?? "",
]
}
Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: [