ios - 展开可选内容时,“AnyObject”无法转换为 'String'

标签 ios swift parse-platform

下面的代码在我放置“if let”语句来解开从 Parse 中提取的可选 ProductData 的行中给出了错误“'AnyObject' 无法转换为 'String'”。我只是想从解析中的对象中提取字符串。我到处都检查过,所有标准答案/解决方案都不起作用。有什么想法吗?

大部分代码直接取自 Parse iOS 文档 Here

import Foundation

import Parse

func getDataFromParse () {

var productDataFromParse = PFQuery(className:"Product")

productDataFromParse.getObjectInBackgroundWithId("uyeXHufDgq") {

(productData: PFObject?, error: NSError?) -> Void in

if error == nil && productData != nil {

    if let productTitle = productData["productTitle"] as! String {
        self.productTitle = productTitle
    }


} else {
    println(error)
}
}

}

最佳答案

productData: PFObject? 对象本身是可选的。您还不能对它进行下标,因为它之前需要被解包。您可以使用可选链接替换 ​​productData != nil 检查。

在 Swift 1.2 中,您可以在同一语句中执行此操作并进行错误检查:

if let productTitle = productData?["productTitle"] as? String
   where error == nil {
    self.productTitle = productTitle
}

请注意 productData 和方括号之间的附加 ?

关于ios - 展开可选内容时,“AnyObject”无法转换为 'String',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30982935/

相关文章:

ios - 尝试后台获取期间出现 AFNetworking 错误 53

ios - 如何在 Swift UI 中实现本地化

iphone - 在 iPhone Development/Objective-C 中初始化实例变量

ios - 从另一个类访问 UISegmentedControl @IBOoutlet

ios - Swift UIImagePickerController 动态转换获取路径失败

ios - 使用 Parse 获取用户位置

ios - 将 Parse.com 用户链接到地址簿联系人

javascript - 基于宽度计算的表格列显示和隐藏在 Safari IOS 设备中不起作用

swift - SKPaymentQueue.default().add( payment) 被忽略

java - com.parse.ParseRequest$ParseRequestException : bad json response With Parse error code 100