ios - Swift AnyObject 作为 String 动态转换失败

标签 ios swift casting parse-platform

我有一个 Int,在 Parse 中保存为 AnyObject。当我检索 AnyObject 时?并尝试将其转换为 String、NSString、NSNumber 或其他任何内容,我不断收到 EXC_Breakpoint,因为转换返回 Nil,并且出现“Swift 动态转换失败”错误。

我尝试创建这个简单的测试来找出哪个部分失败了,但疯狂的是,这个测试将通过,而看似所有步骤都是相同的:

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,但该语法使我无法进行正确的转换。

最佳答案

因为您已将 Int 保存到 Parse 中,而 Int 不是对象,因此必须将其转换为对象。看来 Parse 框架已将其转换为 NSValue,它实际上是表示内在类型的字节缓冲区。

您可以尝试将这些字节转换回 Int,但在将值存储在 Parse 对象中之前将其编码为 NSNumber 会更容易、更好 - 然后在检索对象时您将能够轻松处理它。

关于ios - Swift AnyObject 作为 String 动态转换失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27009024/

相关文章:

ios - 使用 GoogleMaps 时,myLocationEnabled 会在 swift 上更改为 isMyLocationEnabled

ios - 如何访问返回类型为 UIViewController 的对象数组

java - Spring Integration 中使用的 SpEL 表达式的类型转换

ios - [managedObjectContext reset] 时核心数据崩溃;

ios - header 未显示在 UICollectionViewController Swift 中

ios - 枚举NSArray从给定索引开始以两种方式搜索(环绕)

ios - Swift:PrepareForSegue 正在运行但未加载 ViewController

ios - 以编程方式在 iOS 中将另一个 UIViewController 显示为弹出窗口?

ios - 如何创建混合开发 Pod

c++ - 实现隐式转换为 char* 的 String 类 (C++)