james james - 2 months ago 11
iOS Question

Generic parameter 'Element' could not be inferred Swift closure

I'm trying to return an array of Strings in a Swift 3 closure. I'm getting the error

Generic parameter 'Element' could not be inferred
when I try to return the array. Here's the relevant code:

Define function closure:

var userArray: [String] = []
func getUsers(_ userID: String, closure:(([String]) -> Void)?) -> Void{
userArray.append(user as String)
closure!(userArray)
}
}


Return the array:

_ = self.getUsers(userID!, closure: { (userArray) in //Generic parameter error...
self.users.append(userArray)
})


What am I doing wrong?

Thanks!

Answer

You have multiple coding errors. The following compiles (even if it may or may not meet your code's intent).

  1> var userArray: [String] = [] 
  2. func getUsers(_ user: String, closure:(([String]) -> Void)?) -> Void { 
  3.   userArray.append(user)
  4.   closure?(userArray) 
  5. } 
userArray: [String] = 0 values

 11> var users : [String] = [] 
 12. getUsers("me", closure: { (userArray : [String]) in 
 13.         users += userArray
 14.     }) 
users: [String] = 1 value {
  [0] = "me"
}