Reputation: 1651
I have the following class
class Game {
// An array of player objects
private var playerList: [Player]?
}
I want to enumerate through the playerList; this requires to import Foundation
then cast it to a NSArray
; but its always complaining that it can't convert it
func hasAchievedGoal() {
if let list:NSArray = playerList {
}
for (index,element) in list.enumerate() {
print("Item \(index): \(element)")
}
}
Cannot convert value of type '[Player]?' to specified type 'NSArray?'
I've tried the below, but that isn't working:
if let list:NSArray = playerList as NSArray
Upvotes: 7
Views: 13398
Reputation: 5188
You can't convert an optional array to NSArray, you have to first unwrap the array. You can do this via test, like this:
if let playerList = playerList {
let list:NSArray = playerList
}
Upvotes: 4
Reputation:
You don't need to cast to NSArray
to enumerate:
if let list = playerList {
for (index,value) in list.enumerate() {
// your code here
}
}
As for your cast you should do it like this:
if let playerList = playerList,
list = playerList as? NSArray {
// use the NSArray list here
}
Upvotes: 7