Swift - 如何将 swift 数组转换为 NSArray?
Swift - How to convert a swift array to NSArray?
我有以下class
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
我做错了什么?
谢谢
您无需强制转换为 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
}
您不能将可选数组转换为 NSArray,您必须先解包数组。你可以通过测试来做到这一点,像这样:
if let playerList = playerList{
let list:NSArray = playerList
}
我有以下class
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
我做错了什么?
谢谢
您无需强制转换为 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
}
您不能将可选数组转换为 NSArray,您必须先解包数组。你可以通过测试来做到这一点,像这样:
if let playerList = playerList{
let list:NSArray = playerList
}