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

SwiftUI中如何展示API返回JSON数据的第一个元素?

Fixing Your SwiftUI Text Display for Poem Data

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:

  • PoemData is a struct type, not an instance or array. Your actual poem data is stored in the @State var data array.
  • You need to access the first element of the data array, then access its title and content properties.

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:

  1. Improve the @State Initialization
    Your initial data setup can be simplified (no need for String(...)):

    @State public var data: [PoemData] = [PoemData(title: "Poem Name", content: "Poem Content", poet: Poet(name: "Poet Name"))]
    
  2. 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()
    }
    
  3. Display the First Poem's Data in SwiftUI
    In your view's body, use optional binding to safely access the first element of the data array (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.first returns an optional PoemData? (it's nil if the array is empty). Using if let safely unwraps this optional so we can access the title and content properties.
  • The onAppear modifier ensures your getData() function runs when the view loads, updating the data array 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:32:06