使用回调

时间:2016-12-03 12:45:05

标签: ios swift

你好我正在学习swift

我有以下未编译的代码块

class UserService {

    func name(delay: Int, completion: ([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: delay, execute: completion(users))
    }
}

我想在某些语言之后延迟输出,我想知道如何在一定时间后调用此回调。我希望在MainThread上提供这个结果。

1 个答案:

答案 0 :(得分:3)

在Swift 3中,这很容易:

let seconds = 10
DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
    // Some work
}

在你的情况下,它将是:

class UserService {

    func name(delay: DispatchTime, 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: delay) {
            completion(users)
        }
    }
}

// Test it
let service = UserService()
let delay: DispatchTime = .now() + 10
service.name(delay: delay) { users in
    print(users)
}