Swift4中“Use of unresolved identifier 'json'”错误解决咨询
Hey there! Let's work through this problem step by step. First, that "Use of unresolved identifier 'json'" error means you’re trying to reference a variable named json that hasn’t been properly declared, initialized, or populated with parsed JSON data. Let’s fix that first, then build out the logic for your three coupon prompt messages.
The root issue here is that you haven’t properly fetched and parsed your JSON data before trying to use the json variable. Here’s a complete example of how to make a network request, parse the JSON, and get access to a valid json variable:
// Replace this with your actual API endpoint for coupon checks guard let couponAPIURL = URL(string: "https://your-api-domain.com/coupon/check") else { print("Invalid API URL") return } // Start a background network task to fetch data let task = URLSession.shared.dataTask(with: couponAPIURL) { data, response, error in // Handle network errors first if let requestError = error { print("Network request failed: \(requestError.localizedDescription)") return } // Ensure we received data from the API guard let responseData = data else { print("No data returned from API") return } // Parse the data into a JSON object do { // Here we initialize the `json` variable properly—no more unresolved identifier error! if let json = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: Any] { // Pass the parsed JSON to our handler function for prompt logic self.processCouponResponse(json: json) } } catch let parsingError { print("JSON parsing failed: \(parsingError.localizedDescription)") } } // Kick off the network request task.resume()
Now that we have a valid json variable, let’s build a function to check the API’s response and show the correct Japanese prompt. I’ll assume your API returns a status field (like status or result) that tells us which scenario we’re in—adjust the key names to match your actual API response!
func processCouponResponse(json: [String: Any]) { // Extract the status from the JSON (update "status" to your API's actual key) guard let responseStatus = json["status"] as? String else { print("API response missing required status field") return } // Determine the correct prompt message based on the status let promptMessage: String switch responseStatus { case "already_claimed": // Match your API's value for "coupon already collected" promptMessage = "このクーポンは取得済です" case "added_success": // Match your API's value for "coupon added successfully" promptMessage = "マイクーポンに追加されました" case "missing_user": // Match your API's value for "missing registered user params" promptMessage = "マイクーポンに追加できませんでした" default: promptMessage = "不明なエラーが発生しました" // Fallback for unexpected statuses } // Show the prompt on the main thread (UI updates must happen here!) DispatchQueue.main.async { let alert = UIAlertController(title: nil, message: promptMessage, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default)) self.present(alert, animated: true) } }
- Always make sure the
jsonvariable is declared and populated before you use it—this eliminates the unresolved identifier error entirely. - Double-check your API’s response structure: if your backend uses numeric status codes (like
1,2,3) instead of strings, adjust theswitchstatement to handle integers instead. - UI updates (like showing alerts) must run on the main thread—we use
DispatchQueue.main.asyncto ensure this.
内容的提问来源于stack exchange,提问作者sty

