我有一个Int,我在Parse中保存为AnyObject。当我检索AnyObject?并尝试将其转换为String,NSString,NSNumber或其他任何东西,我继续得到一个EXC_Breakpoint,因为演员正在返回Nil并且那里有一个" Swift动态演员失败"错误&#34 ;.
我试图创建这个简单的测试以确定哪个部分失败了,但是疯狂的是这个测试将通过看似所有步骤都相同的地方:
func testAnyObjectCasting(){
var myInt32: Int32 = 265
var myInt: Int = Int(myInt32)
var myAnyObject: AnyObject? = myInt as AnyObject
var myAnyArray: [[AnyObject]] = [[AnyObject]]()
myAnyArray.append(["something", myAnyObject!])
println(myAnyObject)
var myOtherAnyObject: AnyObject? = myAnyArray[0][1]
println(myOtherAnyObject)
var myString:NSNumber? = myOtherAnyObject as? NSNumber
println(myString)
var myInt2: Int = myString! as Int
}
这里是我的逻辑中的相关代码片段,并注意到println()正常工作,直到向下转换为NSNumber,此时返回Nil:
//ABRecordGetRecordId returns an ABRecordID, which is of type Int32
//This value that's stored in the 2nd column of the multiDim [[AnyObject]]
var personId: Int = Int(ABRecordGetRecordID(person))
//This is a call to a Parse object, which returns an AnyObject. I then cast that to
//a multidimensional array AnyObject as that's the true structure of the data in swift speak
var deviceContacts: [[AnyObject]] = device?[deviceContactsFieldName] as [[AnyObject]]
//This returns the expected value, which in my broader test case is 99999, which is supported by Int
var i:Int = 1
println("the value in device contacts \(i) column 1 is: \(deviceContacts[i][1])")
//This takes a single cell value from the multidim array and puts it in an optional AnyObject
var valueInParse: AnyObject? = deviceContacts[i][1]
//This still returns 99999
println(valueInParse)
//This is where 99999 is replaced with nil. Any ideas?
var valueNSNumberInParse: NSNumber? = valueInParse as? NSNumber
//Nil :(
println(valueNSNumberInParse)
//Exception as I'm trying to unwrap nil :(
var unwrappedNSNumber:NSNumber = valueNSNumberInParse!
我感到沮丧的部分原因是我不明白为什么println()适用于AnyObject但是所有的转换都失败了。显然,那里的代码可以将值解释为为println显示的字符串,但是这种语法使我无法正确投射。
答案 0 :(得分:2)
因为您已将Int保存到Parse并且Int不是对象,所以它必须转换为对象。似乎Parse框架已将其转换为NSValue,NSValue实际上是表示内部类型的字节缓冲区。
您可以尝试将这些字节转换回Int,但是在将值存储到Parse对象之前将值编码为NSNumber更容易也更好 - 然后在检索对象时您将能够轻松地处理它。