我正在尝试将anyObject转换为Int.这是我的代码: println(currentObject[0])println(_stdlib_getDemangledTypeName(currentObject[0])) 2 Swift.ImplicitlyUnwrappedOptional Swift.AnyObject 我正在尝试将currentObject [0]转换为I
println(currentObject[0]) println(_stdlib_getDemangledTypeName(currentObject[0]))
2
Swift.ImplicitlyUnwrappedOptional<Swift.AnyObject>
我正在尝试将currentObject [0]转换为Int.这是我试过的:
let num: Int = currentObjec[0] as! Int
当我运行应用程序时,我收到以下错误:
Could not cast value of type ‘__NSCFString’ (0x103c93c50) to ‘NSNumber’ (0x103535b88)
当我尝试这个:currentObject [0] .toInt()
我收到一个错误说
‘AnyObject’ does not have a member named ‘toInt()’
我能够使其工作的唯一方法是执行以下操作:
let numStr = currentObject[0] as! String let num: Int = numStr.toInt()!
有更简单的方法吗? (无需先将其转换为String.)
从错误消息Could not cast value of type ‘__NSCFString’ (0x103c93c50) to ‘NSNumber’ (0x103535b88)
你可以得出结论,currentObject [0]实际上是一个NSString.
在这种情况下,你可以简单地转换它
let numStr = currentObject[0].integerValue
但请注意,如果数组元素不是NSString,则会崩溃.