简体   繁体   English

'AnyObject'无法转换为'String'

[英]'AnyObject' is not convertible to 'String'

I've got this error when i try to query the parse database. 当我尝试查询解析数据库时出现此错误。 I'm using this code found into the parse documentation and modified a bit. 我正在使用解析文档中找到的这段代码,并对其进行了一些修改。 I need to take all records saved into 'elencoBirre' table, my 'test' variable is of type 'AnyObject' and i'm not able to "convert" this to a simple String, i don't get how to do. 我需要将所有记录保存到“ elencoBirre”表中,“ test”变量的类型为“ AnyObject”,并且我无法将其“转换”为简单的String,我不知道该怎么做。 I've tried to force 'as NSString/String' but when i launch the app it stuck. 我试图强制'as NSString / String',但是当我启动应用程序时,它卡住了。

var appoggio2 = [String]()  

func loadDataCarrello(){

    self.appoggio2.removeAll()
    var findTimelineData:PFQuery = PFQuery (className: "Carrello")
    findTimelineData.whereKeyExists("elencoBirre")
    findTimelineData.findObjectsInBackgroundWithBlock{
        (objects:[AnyObject]!, error:NSError!)->Void in
        if error == nil{
            for object in objects{
                let test:PFObject = object as PFObject

                //Here is the error 'AnyObject' is not convertible to 'String'
                self.appoggio2.append(test.objectForKey("elencoBirre"))
            }                
        }
        println(self.appoggio2)
    }        
}

The objectForKey method does not guarantee results of a specific type. objectForKey方法不能保证特定类型的结果。 To cast it and append when the cast is successful, use the following: 若要进行转换并在转换成功后追加,请使用以下命令:

if let elencoBirre = test.objectForKey("elencoBirre") as? String {
  self.appoggio2.append(elencoBirre)
}

You have stated that you actually expect this object to be an array. 您已经说过,您实际上希望该对象是一个数组。 Try this instead: 尝试以下方法:

if let elencoBirre = test.objectForKey("elencoBirre") as? [String] {
  for str in elencoBirre {
    self.appoggio2.append(str)
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM