Passing constants out of a function - Swift

95 Views Asked by At

I hope this doesn't sound dumb but I'm trying to put:

let lowercasedQuery = query.lowercased()
            
             let usersNew = users.filter({ $0.fullname.lowercased().contains(lowercasedQuery) || $0.username.contains(lowercasedQuery) })

into the DispatchQueue function but obviously, since they are constants declared in the function, the function is out of scope for the return line.

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

Does anyone know how to solve this?

Thanks!

1

There are 1 best solutions below

4
On BEST ANSWER

You need a closure... more info here. Instead of return, call the completion handler closure.

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({ $0.fullname.lowercased().contains(lowercasedQuery) || $0.username.contains(lowercasedQuery) })
        completion(usersNew)
    }
}

Usage:

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

If you are trying to return users inside another function, it won't work. You also need to a add a closure to that function:

                                   /// 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")`