函数在返回Swift后赋值

时间:2016-06-17 17:02:59

标签: swift function closures

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

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用户:

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",如下: enter image description here

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

供参考:JSON只是我为[String:AnyObject]字典定义的类型。

1 个答案:

答案 0 :(得分:1)

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
}