7

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

2 Answers 2

8

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

If I do if let list = self.playerOrderList as? NSArray { it says; Cast from '[Player]?' to unrelated type 'NSArray' always fails
Yeah I forgot to unwrap the optional first, typing this on my phone and couldn't test the code. Updating the answer.
4

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.