You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift4中如何将结构体追加到数组中?附相关代码示例

Append 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 foods as an empty non-optional array to avoid nil checks every time we append.
  • JSON Parsing: We safely unwrap each required field (fid and fname) and handle optional fields (hits and addr) 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:44:24