Swift - How to convert a swift array to NSArray?

zardon

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)")
        }
   }

Errors:

Cannot convert value of type '[Player]?' to specified type 'NSArray?'

I've tried:

if let list:NSArray = playerList as NSArray

What am i doing wrong?

Thanks

user887210

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
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to convert NSArray to [Int] with Swift

Convert NSArray to NSMutableArray Swift

How to convert NSArray's element type in Swift

how to convert NSArray into String swift3?

How to filter NSArray in Swift?

How to convert Swift array into CFArray?

How to convert CFArray to Swift Array?

Swift's Array type is bridged to Foundation's NSArray class, how?

How to swap NSArray elements in swift

Swift: 'NSArray?' is not convertible to 'NSArray?'

Convert NSArray (Swift) to vector (C++)

Array is empty after the conversion of NSArray to Swift Array

How to convert string type array into array in swift?

How to Convert NSMutable Array to Swift Array?

How to convert array to another array in Swift

Convert NSArray into Array of unique values sorted by frequency in Objective-C or Swift

Error converting static Swift Array in Enum to NSArray

Converting Swift array of [Int64] into NSArray

Is there a Swift Array equivalent for NSArray.arrayByAddingObjectsFromArray()?

Loop through NSArray and copy to new swift Array

How to convert String to array of float in swift

How do I convert a Swift Array to a String?

How to convert an array of mixed sized integers in swift

How to convert a double into a byte array in swift?

How to convert a String (numeric) in a Int array in Swift

How to convert a float value to byte array in swift?

How to convert an ContiguousArray of Floats into a byte array in Swift?

How can I convert an array to string in swift?

How to convert array of strings in swift to UnsafeMutableRawPointer?