Swift - 如何将swift数组转换为NSArray?

时间:2016-03-05 07:41:19

标签: swift casting nsarray

我有以下课程

class Game {
// An array of player objects
    private var playerList: [Player]?
}

我想通过playerList枚举;这需要import Foundation然后将其转换为NSArray;但它总是在抱怨它无法转换它

 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?'

我试过了:

if let list:NSArray = playerList as NSArray

我做错了什么?

由于

2 个答案:

答案 0 :(得分:4)

您无需转发NSArray进行枚举:

if let list = playerList {
  for (index,value) in list.enumerate() {
    // your code here
  }
}

至于你的演员,你应该这样做:

if let playerList = playerList,
    list = playerList as? NSArray {
  // use the NSArray list here
}

答案 1 :(得分:4)

您无法将可选数组转换为NSArray,您必须首先打开数组。您可以通过测试来完成此操作,如下所示:

if let playerList = playerList{
    let list:NSArray = playerList
}