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
}
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.)
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?
For reference: JSON is simply a typealias I defined for [String: AnyObject] dictionary.