Swift解析学生数据:自定义打印格式去除项目名与数组键
Fixing the Student Data Output Format in Swift
Hey there! The issue you're seeing is that when you print a.moreDetails directly, Swift uses the default debug description for your moreDetailsArray struct (which includes the type name and property labels). To get the clean John Tylor : Full Time : Graduated format you want, we need to extract specific properties from the struct and format them manually.
Here's how to modify your code:
Key Changes:
- Safe Optional Handling: Replace force unwraps (
!) with optional binding to avoid runtime crashes if the API data is malformed. - Manual Formatting: Instead of printing the entire
moreDetailsarray, iterate over its elements (since it's an array) and construct the output string using thetypeandstatusproperties. - Improved Naming: Renamed structs to follow Swift's standard naming conventions (type names use UpperCamelCase) for better readability.
Modified Code:
struct StudentData: Decodable { let moreDetails: [MoreDetails] let id: Int let name: String } struct MoreDetails: Decodable { let type: String let status: String } func parseStudentData() { guard let url = URL(string: "https://api.myjson.com/bins/11mamq") else { print("Invalid URL") return } URLSession.shared.dataTask(with: url) { (data, response, error) in do { if let error = error { throw error } guard let data = data else { print("No data received") return } let students = try JSONDecoder().decode([StudentData].self, from: data) for student in students { // Iterate over each entry in moreDetails (works even if there are multiple entries) for details in student.moreDetails { print("\(student.name) : \(details.type) : \(details.status)") } } } catch { print("Error getting status: \(error)") } }.resume() }
Explanation:
- URL Validation: The
guard letchecks if the URL is valid before proceeding, preventing unnecessary errors. - Graceful Error Handling: We properly unwrap
erroranddatato handle edge cases like missing data or network issues without crashing. - Custom Output Construction: For each student, we loop through their
moreDetailsarray (since it's a collection of structs) and print a formatted string using the exact values you need.
This will output exactly the format you requested: John Tylor : Full Time : Graduated for each matching student entry!
内容的提问来源于stack exchange,提问作者G Menaria
相关产品推荐
相关产品推荐

