Swift4中如何将结构体追加到数组中?附相关代码示例
Foods Struct to Array in Swift 4 Let's walk through fixing your code to properly append Foods struct instances to your array, especially handling the network response parsing part. Here's the adjusted implementation:
Step 1: Initialize Your Array Properly
First, your foods array is declared as an optional but never initialized. Instead of leaving it as a nil optional, initialize it as an empty array (you can still make it optional if needed, but an empty non-optional array is safer here):
var foods: [Foods] = [] // Initialize empty array instead of nil optional
Step 2: Complete the POST Request & Parse Response
You'll need to finish constructing the POST parameters, execute the data task, parse the JSON response, convert each item to a Foods struct, and append it to the array. Here's the full updated getFoodsById function:
import Foundation struct Foods { var fid: Int var fname: String var hits: Int? var addr: String? } class Food { func getFoodsById(_ fid: Int, completion: @escaping ([Foods]?) -> Void) { // Initialize empty array to hold results var foods: [Foods] = [] let urlString = "http://jsm0803.iptime.org:81/html/sufoo/getFoodById.php" guard let requestURL = URL(string: urlString) else { completion(nil) return } var request = URLRequest(url: requestURL) request.httpMethod = "POST" // Construct POST parameters (assuming your PHP expects form data) let postParameters = "fid=\(fid)" request.httpBody = postParameters.data(using: .utf8) request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") // Execute data task let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { print("Error fetching data: \(error?.localizedDescription ?? "Unknown error")") completion(nil) return } // Parse JSON response do { // Assuming your PHP returns an array of food objects guard let jsonArray = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] else { print("Invalid JSON format") completion(nil) return } // Convert each JSON object to Foods struct and append to array for foodJson in jsonArray { guard let fid = foodJson["fid"] as? Int, let fname = foodJson["fname"] as? String else { continue // Skip invalid entries } let hits = foodJson["hits"] as? Int let addr = foodJson["addr"] as? String let food = Foods(fid: fid, fname: fname, hits: hits, addr: addr) foods.append(food) // Append the struct to the array } // Return the populated array via completion handler completion(foods) } catch { print("JSON parsing error: \(error.localizedDescription)") completion(nil) } } task.resume() } }
Key Notes:
- Completion Handler: Since network requests are asynchronous, we added a completion handler to return the populated array once the request finishes (you can't return it directly from the function).
- Array Initialization: We initialized
foodsas an empty non-optional array to avoid nil checks every time we append. - JSON Parsing: We safely unwrap each required field (
fidandfname) and handle optional fields (hitsandaddr) gracefully. - POST Parameters: We used form-urlencoded data (common for PHP endpoints) – adjust the content type and parameter format if your endpoint expects JSON instead.
How to Use This:
Call the function like this to get the populated array:
let foodManager = Food() foodManager.getFoodsById(123) { foods in if let foods = foods { print("Fetched \(foods.count) foods:") for food in foods { print("\(food.fid): \(food.fname)") } } else { print("Failed to fetch foods") } }
内容的提问来源于stack exchange,提问作者Soonmyun Jang

