SwiftUI中如何展示API返回JSON数据的第一个元素?
Hey there! I see you're getting started with Swift and iOS development—great work getting the API request and decoding set up already! Let's sort out how to display that first poem's title and content in your Text views.
The Issue with Your Current Approach
Your Text(PoemData.title[0]) syntax doesn't work because:
PoemDatais a struct type, not an instance or array. Your actual poem data is stored in the@State var dataarray.- You need to access the first element of the
dataarray, then access itstitleandcontentproperties.
Step-by-Step Solution
First, let's clean up a few small things in your existing code to make it safer, then implement the Text display:
Improve the @State Initialization
Your initialdatasetup can be simplified (no need forString(...)):@State public var data: [PoemData] = [PoemData(title: "Poem Name", content: "Poem Content", poet: Poet(name: "Poet Name"))]Make the API Request Safer
Avoid force-unwrapping the URL with!—use optional binding instead:func getData() { let urlString = "https://www.poemist.com/api/v1/randompoems" guard let url = URL(string: urlString) else { print("Invalid URL") return } URLSession.shared.dataTask(with: url) { data, response, error in DispatchQueue.main.async { if let data = data { do { let decoder = JSONDecoder() let decodedData = try decoder.decode([PoemData].self, from: data) self.data = decodedData } catch { print("Decoding error: \(error)") } } else if let error = error { print("Request error: \(error)") } } }.resume() }Display the First Poem's Data in SwiftUI
In your view'sbody, use optional binding to safely access the first element of thedataarray (this prevents crashes if the array is empty):var body: some View { VStack(spacing: 20) { if let firstPoem = data.first { Text(firstPoem.title) .font(.title) .fontWeight(.bold) Text(firstPoem.content) .font(.body) .padding() } else { // Show a loading state or placeholder if no data exists Text("Loading poem...") } } .onAppear { getData() // Call your API request when the view appears } }
Why This Works
data.firstreturns an optionalPoemData?(it'snilif the array is empty). Usingif letsafely unwraps this optional so we can access thetitleandcontentproperties.- The
onAppearmodifier ensures yourgetData()function runs when the view loads, updating thedataarray with real API data.
That's it! Now your Text views will show the first poem's title and content once the API request completes.
内容的提问来源于stack exchange,提问作者Simbeul

