i6x86 i6x86 - 4 months ago 30
Swift Question

Cannot convert value of type '[AnyObject]' to expected argument type '[String]'

When I try to compile this code:

func lookupPlayers() {
print("Looking up \(match?.players.count)")

// Loading ID from players connected in the match
var idsArray = NSMutableArray()
if (match != nil) {
for players in match!.players {
if let player = players as? GKPlayer {
idsArray.addObject(player.playerID!)
}
}

}

GKPlayer.loadPlayersForIdentifiers(idsArray as [AnyObject] as [AnyObject], withCompletionHandler: { (players, error) -> Void in
if (error != nil) {
// Handle error here
// if we fail to retrieve player info return and end the match
print("Error retrieving player info: \(error.localizedDescription)")
self.matchStarted = false
self.delegate?.matchEnded?()
}
else {
// Get info from all players and start the match
self.playersDict = NSMutableDictionary(capacity: players.count)
for player1 in players {
if let player = player1 as? GKPlayer {
print("Found player: \(player.alias)")
self.playersDict.setObject(player, forKey: player.playerID)
}
}
self.playersDict.setObject(self.localPlayer, forKey: self.localPlayer.playerID)

self.matchStarted = true
self.delegate?.matchStarted?()
}
})
}


I'm getting this error:


Cannot convert value of type '[AnyObject]' to expected argument type '[String]' in this line:

GKPlayer.loadPlayersForIdentifiers(idsArray as [AnyObject] as [AnyObject], withCompletionHandler: { (players, error) -> Void in



What am I doing wrong?

Answer

Try the following:

  1. Replace var idsArray = NSMutableArray() with var idsArray = [String](). This way you use Swift arrays, not Obj-C NSArrays.

  2. Then replace:

GKPlayer.loadPlayersForIdentifiers(idsArray as [AnyObject] as [AnyObject], withCompletionHandler: { (players, error) -> Void in if (error != nil) {

With:

GKPlayer.loadPlayersForIdentifiers(idsArray as [String], withCompletionHandler: { (players, error) -> Void in if (error != nil) {