问题描述
我是 swift 的新手,想知道如何在函数完成时将参数传递给函数.我尝试只传入一个变量 String ,但这不起作用.这是我用于处理 api 请求的类.这是我需要将内容传递到的地方,以便它可以将其添加到搜索字段并返回结果.
I'm new to swift and am wondering how I can pass arguments into a function when that function has a completion. I tried just passing in a variable String but that did not work. Here is my class for handling an api request. This is where i need to pass the contents to so that it can add it to a search field and return the results.
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()
}
}
这是我的内容视图代码,我试图将文本框的内容传递到此函数中,以便我可以从 api 获取结果:
This is my content view code where I am trying to pass in the contents of a text box into this function so that i can get the result back from the api:
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 { (result) in //IDEALLY I WOULD LIKE TO PASS IN THE CONTENTS OF THE TEXT BOX HERE INTO apiRequest
self.result = result
}
}
}
}
}
}
我确信解决方案很简单,我只是不习惯语法和诸如此类的语法,但非常感谢对此的任何帮助.
I'm sure the solution is simple I am just not used to the syntax and such of swift quite yet any help with this is much appreciated.
推荐答案
你的函数 'apiRequest' 有 2 个参数:
Your function 'apiRequest' has 2 parameters:
- 搜索:字符串(此参数需要一个字符串)
- 完成:@escaping (Result) ->()
所以当你调用这个方法时,你也会传递这两个参数,就像这样:
So when you call this method, you will pass these 2 parameters as well, like this:
.onTapGesture {
API().apiRequest(search: "String you want to pass", completion: { (result) in
self.result = result
})
}
了解闭包,因为此完成参数也是一种闭包(转义闭包).
这篇关于如何快速完成将参数传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!