gpt4 book ai didi

ios - 使用 Swift 闭包捕获变量

转载 作者:行者123 更新时间:2023-11-28 06:57:27 25 4
gpt4 key购买 nike

我有这段代码,它显然出错了,因为当我在 return 语句中使用 FOO 时,它超出了函数的范围。我知道(我想我知道)我需要使用闭包来捕获变量,但我不知道该怎么做。使用 Alamofire 和 SwiftyJSON。任何帮助都会很棒!谢谢!

  func getPlayerID(named: String) -> String {

Alamofire.request(.GET, "URL", headers: headers)
.responseJSON { response in


let json = JSON.self(response.result.value!)

for var index = 0; index < json.count; index++ {
if json[index]["Name"].stringValue == named {
var FOO = json[index]["FOO"].stringValue
} // If Statement End
} // For Loop End
} // Alamofire Request End

// Return Statement for getPLayerID Function

return FOO

} // getPlayerID Function End
} // Player Struct End

最佳答案

基本思想是 getPlayerID 不应该返回任何东西,而应该只有一个闭包参数,一旦你检索到你想要“返回”的值,你就调用闭包使用该值作为参数。

但是,我建议在这里进行各种其他改进:

  • 构建一个字符串数组并返回它
  • 检查 result 是否为 .Failure,因为您无法控制可能出现的各种服务器/网络问题
  • 更改闭包以检测和报告错误

但希望这能说明基本思想:

就我个人而言,我 (a) 将 String 参数设置为 completionHandler 可选; (b) 添加另一个可选的错误参数;和 (c) 向 getPlayerID 添加错误处理:

func getPlayerID(completionHandler: ([String]?, ErrorType?) -> Void) {
Alamofire.request(.GET, "URL", headers: headers)
.responseJSON { request, response, result in
switch (result) {
case .Success(let value):
let json = JSON.self(value)

// variable to hold all of the results

var strings = [String]()

// populate the array of strings

for var index = 0; index < json.count; index++ {
if json[index]["Name"].stringValue == named {
strings.append(json[index]["FOO"].stringValue)
}
}

// call the completion handler with the strings

completionHandler(strings, nil)
case .Failure(_, let error):
completionHandler(nil, error)
}
}
}

然后,当你想调用它时:

getPlayerID() { strings, error in
// use `strings` here
}

// but not here

关于ios - 使用 Swift 闭包捕获变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33050994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com