从函数中传递常量 - Swift

Passing constants out of a function - Swift

我希望这听起来不傻,但我想说:

let lowercasedQuery = query.lowercased()
            
             let usersNew = users.filter({ [=11=].fullname.lowercased().contains(lowercasedQuery) || [=11=].username.contains(lowercasedQuery) })

进入 DispatchQueue 函数,但显然,由于它们是在函数中声明的常量,因此该函数超出了 return 行的范围。

func filteredUsers(_ query: String) -> [User] {
        
        
        let delay = 3.3
    
        DispatchQueue.main.asyncAfter(deadline: .now() + delay)
        {
            
        }
            
            let lowercasedQuery = query.lowercased()
            
             let usersNew = users.filter({ [=12=].fullname.lowercased().contains(lowercasedQuery) || [=12=].username.contains(lowercasedQuery) })
        
        return usersNew
    }

有人知道怎么解决吗?

谢谢!

您需要关闭...更多信息 。而不是 return,调用完成处理程序闭包。

func filteredUsers(_ query: String, completion: @escaping (([User]) -> Void)) {
    let delay = 3.3
    
    DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
        let lowercasedQuery = query.lowercased()
        let usersNew = self.users.filter({ [=10=].fullname.lowercased().contains(lowercasedQuery) || [=10=].username.contains(lowercasedQuery) })
        completion(usersNew)
    }
}

用法:

viewModel.filteredUsers(searchText) { users in
    print(users) /// get your users here!
}

如果您试图在另一个函数中 return users,它将无法工作。您还需要向 that 函数添加一个闭包:

                                   /// another closure here
func mainFunction(_ query: String, completion: @escaping (([User]) -> Void)) {
    viewModel.filteredUsers(query) { users in
        completion(users) /// equivalent to `return users`
    }
}

mainFunction("searchText") { users in
    print(users) /// get your users here!
}

/// NOT `let users = mainFunction("searchText")`