(SKNode) 不可转换为字符串(它使用旧的 xCode)

(SKNode) not convertible to string (it was working with old xCode)

在我的应用程序中,我使用了这段代码并且它运行良好:

var data3: NSArray = [] //1
for gg  in data3{ //2
    var hh:String = gg["percentage"] as String //3
    perchomerec = hh.toInt()! //4
}

现在我更新了我的 xCodeOSx 版本,现在同一段代码给出了这个错误(在 //3 行):

[SKNode] is not convertible to String

我需要更改什么?

因为 Swift 1.2 as 运算符只能用于向上转型。向下转型时,您应该使用 as!as?(详细说明可以在 The Swift Programming Language 中找到)。

var hh:String = gg["percentage"] as! String

听起来您需要使用 !?,尽管从 Jakub Vano 的回答来看,使用可选解包听起来更适合您的代码。如果您不希望 hh 不是 String 或者不是 nil 那么我也建议您检查别处的代码。

var data3: NSArray = []
for gg  in data3 {
  if let h = hh as? String {
    perchomerec = h.toInt()!
  }
}
根据您对我的评论的回复,

data3 似乎属于 [[String:Int]] 类型。

因此,将 NSArray 更改为 [[String:Int]] 或完全删除 NSArray 并让 Swift 自行确定类型。

我猜你的问题是伪代码,所以我猜你是如何设置 data3 的数据的:

let data3 = [["percentage" : 33]] // Swift will determine this type to: [[String:Int]]

for gg in data3 { // gg will become [String:Int]
    perchomerec = gg
}

或者如果你仍然想要 NSArray 类型然后在 for 循环中转换 gg 你必须转换数组本身:

for gg in data3 as! [[String:Int]]

编辑

如果数组发生变化,那么它必须是 NSArray[AnyObject],然后您必须测试每种可能的类型。

for gg in data3 {
    if let dict = gg as? NSDictionary {
        if let str = dict["percentage"] as? String, nr = str.toInt() {
            perchomerec = nr
        }
        else if let nr = dict["percentage"] as? Int {
            perchomerec = nr
        }
    }
}