Reputation: 4079
Very new to iOS development and I've just started dabbling in GCD, I've read several articles on SO and have consulted Apple's documentation, however I am struggling to understand how to set a return value from an "expensive" operation.
The below function will loop over sum 100K users (as an example), doing this on the main thread would obviously halt the GUI for several seconds, therefore in my UserList class, I propose to execute this block asynchronously on my its thread:
let queue = dispatch_queue_create("me.alexsims.user_queue", DISPATCH_QUEUE_CONCURRENT)
public func getUserById(userId: String, completionHandler: (result: User) -> ())
{
dispatch_async(queue)
{
for user in self.users {
if user.getUserId() == userId
{
completionHandler(result: user)
}
}
// Return an empty user object
completionHandler(result: User())
}
}
Now from my understanding, the result
variable should be returned and I should then be able to access the User()
object which is stored in there from my main thread
However, when I return to my controller and run a test:
var list = UserList()
var a_user = User()
a_user = list.getUserByID(userId: "xyz", completionHandler: { (result) -> () in
println(result)
})
this throws the error Could not find an overload for 'println' that accepts the supplied arguments
, I'm guessing thats because I am not on the main queue? So I try:
a_user = list.getUserById(userId: "xyz", completionHandler: { (result) -> () in
dispatch_async(dispatch_get_main_queue()) {
println(result)
}
})
However, I still get the same error. What am I doing wrong here?
SOLVED
As Daniel spotted, the problem was providing the optional parameter to the list.getUserByID
call.
After changing it to:
a_user = list.getUserById("abcde", completionHandler: { (result) -> () in
println(result)
})
The println error vanished.
Upvotes: 0
Views: 1410
Reputation: 24237
Your Swift class User
needs to implement the Printable protocol so that it can be used by println.
Something like this:
Class User: Printable {
let name = "Bob"
var description: String {
return "User: \(name)"
}
}
Read more in this Apple post
If you are feeling lazy, make your User class a subclass of NSObject which already implements the Printable protocol
A quick search of your println error turned this up. Not sure why the error falls through to println but heres a fix:
Try removing the first parameter of your function call, in Swift you don't need to type the first parameter to avoid redundancy:
a_user = list.getUserById(userId: "xyz...
Should be:
a_user = list.getUserById("xyz...
Upvotes: 4