函数在返回Swift后赋值 [英] Function assigning values after it returns Swift
问题描述
我遇到一个奇怪的错误,其中我的函数在数组返回后附加一个值...这段代码如下:
I'm running into a weird bug where my function appends a value to an array AFTER it returns... The code for this is below :
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用户:
I call make user from here:
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)")
}
(这仍然是测试,所以我显然调用我的代码在奇怪的地方。)
(This is all still testing so I'm obviously calling my code in weird places.)
所以当我运行这个最终发生的是,我的newUser数组被打印(它显示为空),然后我的本地分配的userReturn数组makeUser函数打印,它包含我在registerUser的成功完成块中附加的新用户,如下所示:
So when I run this what ends up happening is that FIRST my "newUser" array gets printed (and it shows up empty), and afterwards the userReturn array that I assign locally within the makeUser function prints, and it contains the new user that I append to it within the "success" completion block of "registerUser", like so:
有人知道这里发生了什么,以及如何解决这个问题?
Does anyone know whats happening here, and how I could fix it?
参考:JSON只是一个typealias为[String:AnyObject]字典定义。
For reference: JSON is simply a typealias I defined for [String: AnyObject] dictionary.
推荐答案
registerUser
异步运行,因此应该应用异步模式,例如完成处理程序:
The registerUser
runs asynchronously, so you should apply asynchronous pattern, such as completion handler:
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后赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!