gpt4 book ai didi

swift - 函数返回 Swift 后赋值

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

我遇到了一个奇怪的错误,我的函数在返回后将一个值附加到数组...代码如下:

func makeUser(first: String, last: String, email: String) -> [User] {

var userReturn = [User]()

RESTEngine.sharedEngine.registerUser(email, firstName: first, lastName: last, age: 12, success: { response in
if let response = response, result = response["resource"], id = result[0]["_id"] {

let params: JSON =
["name": "\(first) \(last)",
"id": id as! String,
"email": email,
"rating": 0.0,
"nuMatches": 0,
"nuItemsSold": 0,
"nuItemsBought": 0]
let user = User(json: params)

userReturn.append(user)
print("\(userReturn)")

}
}, failure: { error in
print ("Error creating a user on the server: \(error)")
})

return userReturn
}

我从这里调用 make user:

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var newUser = makeUser("Average", last: "Person", email: "a.Person@mail.com")
print("\(newUser)")
}

(这一切仍在测试中,所以我显然在奇怪的地方调用了我的代码。)

所以当我运行这个时,最终发生的是首先打印我的“newUser”数组(它显示为空),然后打印我在 makeUser 函数中本地分配的 userReturn 数组,它包含新的我在“registerUser”的“成功”完成 block 中附加到它的用户,如下所示: enter image description here

有谁知道这里发生了什么,我该如何解决?

供引用:JSON 只是我为 [String: AnyObject] 字典定义的类型别名。

最佳答案

registerUser 异步运行,因此您应该应用异步模式,例如完成处理程序:

func makeUser(first: String, last: String, email: String, completionHandler: ([User]?, ErrorType?) -> ()) {
RESTEngine.sharedEngine.registerUser(email, firstName: first, lastName: last, age: 12, success: { response in
if let response = response, result = response["resource"], id = result[0]["_id"] {
var users = [User]()

let params: JSON =
["name": "\(first) \(last)",
"id": id as! String,
"email": email,
"rating": 0.0,
"nuMatches": 0,
"nuItemsSold": 0,
"nuItemsBought": 0]
let user = User(json: params)
users.append(user)

completionHandler(users, nil)
} else {
let jsonError = ... // build your own ErrorType or NSError indicating that the the parsing of the JSON failed for some reason
completionHandler(nil, jsonError)
}
}, failure: { error in
completionHandler(nil, error)
})
}

然后像这样使用它:

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
makeUser("Average", last: "Person", email: "a.Person@mail.com") { users, error in
guard error == nil else {
print(error)
return
}

print("\(users)")
// if you're doing anything with this, use it here, e.g. reloadTable or update UI controls
}

// but don't try to use `users` here, as the above runs asynchronously
}

关于swift - 函数返回 Swift 后赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37886812/

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