如何调用Swift闭包回调

时间:2016-12-03 13:27:16

标签: swift closures

我正在尝试在演示者中获取服务数据,然后使用ViewController中的视图引用从演示者调用方法 我可以从服务中得到回调吗? 我有服务/演示者/视图 我的代码如下

的ViewController

class ViewController: UIViewController, UserView {

    private var userPresenter: UserPresenter?

    override func viewDidLoad() {
        super.viewDidLoad()
        userPresenter = UserPresenter(userView: self)
        userPresenter?.getUsers()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func startLoading() {
        print("Start loading is called")
    }

    func stopLoading() {
        print("Stop loading is called")
    }

    func onEmpty() {
        print("Empty users returned")
    }

    func onUsers(users: [User]) {
        for userItem in users {
            print("User name \(userItem.getName())")
        }
    }

}

查看

protocol UserView: NSObjectProtocol {
    func startLoading()

    func stopLoading()

    func onUsers(users: [User])

    func onEmpty()
}

服务

public class UserService {

    func getUsers(delay: Double, completion: @escaping ([User]) -> Void) {
        var users = [User]()


        users.append(User(name: "User 1", email:"user1@gmail.com", age: 25))
        users.append(User(name: "User 2", email: "user2@gmail.com", age: 26))
        users.append(User(name: "User 3", email: "user3@gmail.com", age: 27))

        DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
            print("Sending users")
            completion(users)
            print("Sent user")
        }
    }
}

演示

class UserPresenter {

    private var userService: UserService
    weak private var userView: UserView?

    init(userView: UserView) {
        self.userView = userView
        userService = UserService()
    }

    func detachView() {
        self.userView = nil
    }

    func getUsers() {
        self.userView?.startLoading()
        userService.getUsers(delay: 5000, completion: {
            users: [User] -> Void
                print("adad")
        })

}

当异步任务完成时,我应该如何获得回调方法

func getUsers() {
    self.userView?.startLoading()

    userService.getUsers(delay: 5000){ users in

        print("\(users.count) users added")

        //            self.userView?.onUsers(users: users)
        //            self.userView?.stopLoading()

    }
}

这不符合@vadian

的回答

1 个答案:

答案 0 :(得分:2)

应该调用回调函数

func getUsers() {
    self.userView?.startLoading()
    userService.getUsers(delay: 5000) { users in
        print("\(users.count) users added")
    }
}

使用尾随闭包语法,可以省略completion参数名称。返回参数后面的in关键字是必需的。