【问题标题】:'AnyObject' is not convertible to 'String' while unwrapping optional'AnyObject' 在展开可选时不能转换为 'String'
【发布时间】:2015-09-08 01:56:16
【问题描述】:

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

大部分代码直接取自 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)
}
}

}

【问题讨论】:

  • 您的问题解决了吗,还是还有其他问题?如果有,请选择其中一个答案。如果没有,请告诉我,我会尽力提供帮助。

标签: ios swift parse-platform


【解决方案1】:

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

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

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

注意productData 和方括号之间的额外?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-16
    • 2018-04-18
    • 2016-05-28
    • 2015-11-04
    • 2014-10-10
    • 1970-01-01
    • 2018-06-06
    相关资源
    最近更新 更多