Alamofire参数组装问题:循环添加字典仅保留最后一项
Hey there, let's dig into why your dictionary array only ends up with the last item when you're building it for Alamofire!
First off, let's look at your code—your logic for appending dictionaries to the array seems solid on the surface. But the issue is almost certainly coming from your _SurveySubmitModel data source, not the array-assembly code itself.
Let's break down the possible cause
If every entry in your final Dict array has identical values, it's likely that all elements in _SurveySubmitModel are references to the same object. Here's a common mistake that causes this:
Suppose when you created
_SurveySubmitModel, you reused the same instance of your model object over and over instead of creating a new one each time. For example:var reusableModel = SurveySubmitModel() var _SurveySubmitModel = [SurveySubmitModel]() for someData in dataSource { // You modify the SAME model's properties each time reusableModel.ID = someData.id reusableModel.Response = someData.response // Then add the same reference to the array _SurveySubmitModel.append(reusableModel) }In this case, every entry in
_SurveySubmitModelpoints to the exact same object. By the end of the loop, all entries will reflect the last set of values you assigned.
How to fix it
First, confirm the root cause by checking your loop's print output:
- Look at the
Item \(index + 1): \(value)logs. If every printedvaluehas identical properties, you know the problem is with how_SurveySubmitModelwas built.
Then, fix the model creation process:
Make sure you create a new instance of your model inside the loop when populating _SurveySubmitModel:
var _SurveySubmitModel = [SurveySubmitModel]() for someData in dataSource { // Create a NEW model instance every time let newModel = SurveySubmitModel() newModel.ID = someData.id newModel.SurveyID = someData.surveyId newModel.QuestionID = someData.questionId newModel.FilledBy = someData.filledBy newModel.Response = someData.response _SurveySubmitModel.append(newModel) }
Optimized version of your array-assembly code
Also, a small Swift style note: variable names should start with a lowercase letter, and you don't need Dict.removeAll() since you just initialized an empty array. Here's a cleaned-up version:
// Initialize empty array (no need for removeAll()) var surveyResponses = [[String: Any]]() for (index, value) in _SurveySubmitModel.enumerated() { print("Item \(index + 1): \(value)") let parameters: [String: Any] = [ "ID": value.ID, "SurveyID": value.SurveyID, "QuestionID": value.QuestionID, "FilledBy": value.FilledBy, "Response": value.Response ] surveyResponses.append(parameters) } print("Final responses array: \(surveyResponses)")
Final check
After fixing the model creation, run your code again. The print logs should show distinct values for each value in the loop, and your final array will include all the entries you expect.
内容的提问来源于stack exchange,提问作者Abrar

