如何致电Swift关闭回调



我正在尝试在主持人中获取服务数据,然后使用ViewController中的View Reference从演示者中获取服务数据我可以从服务中获得回调吗?我有服务/主持人/查看我的代码如下

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

在答案中的工作

回调函数应该称为

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

使用 taxt闭合语法可以省略 completion参数名称。返回参数之后的in关键字是强制性的。

最新更新