我在JSON文件中嵌套数据,我使用嵌套结构.如何访问在swift中嵌套在第一个结构中的值?



这是我的代码。我正在从CalorieNinjas API提取JSON数据:

struct Result: Codable {

var items: [FoodItem]?

}
struct FoodItem: Codable {
var name: String?
var calories: String?
}
public class API {

func apiRequest(search: String, completion: @escaping (Result) -> ()) {

//URL
var query = search.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let url = URL(string: "https://calorieninjas.p.rapidapi.com/v1/nutrition?query=" + query!)

//URL REQUEST
var request = URLRequest(url: url!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)

//Specify header
let headers = [
"x-rapidapi-key": "3be44a36b7msh4d4738910c1ca4dp1c2825jsn96bcc44c2b19",
"x-rapidapi-host": "calorieninjas.p.rapidapi.com"
]

request.httpMethod="GET"
request.allHTTPHeaderFields = headers

//Get the URLSession
let session = URLSession.shared

//Create data task
let dataTask = session.dataTask(with: request) { (data, response, error) in

let result = try? JSONDecoder().decode(Result.self, from: data!)
print(result)
DispatchQueue.main.async {
completion(result!)
}


}

//Fire off data task
dataTask.resume()

}
}

这是我的视图的样子:

struct ContentView: View {

@State var result = Result()
@State private var searchItem: String = ""

var body: some View {
ZStack(alignment: .top) {
Rectangle()
.fill(Color.myPurple)
.ignoresSafeArea(.all)
VStack {
TextField("Enter food", text: $searchItem)
.background(Color.white)
.padding()
.textFieldStyle(RoundedBorderTextFieldStyle())
SearchButton()
.padding(.top)
.onTapGesture {
API().apiRequest(search: searchItem, completion: { (result) in
self.result = result
})
}
}
}
}
}

这是打印语句输出到终端的结果,因此我知道我的数据正在被提取和存储:

Optional(CalorieCountApp.Result(items: Optional([CalorieCountApp.FoodItem(name: Optional("pizza"), calories: Optional(262.9))])))

我想做的是像文本(result.items.name/calories)的东西,但我无法访问这样的变量。我是新的swift和制作应用程序作为一个整体,任何帮助是非常感激

看起来你有几个Optional在那里,这意味着你可能会使用?操作符来展开它们。

给定您的类型,这应该可以工作:

let index = 0
let name = result?.items?[index].name // will be `String?`
let calories = result?.items?[index].calories // according to your code you provided, this says `String?` but in your console output it looks like `Double?`

或者在你的例子中:

Text(result?.items?[index].name ?? "unknown")

你可能想做一些更多的阅读关于展开可选或处理nil在Swift -有一些不同的策略。例如,您可以看到我在上一个示例中使用了??

这里有一个有用的链接:https://www.hackingwithswift.com/sixty/10/2/unwrapping-optionals

最新更新