收到来自 Algolia API 的 JSON 响应后,我正在尝试访问 JSON 对象中的特定字段/值。
运行以下
print
函数时,控制台会打印我在 JSON 对象中查找的值。即,“标题”字段/值。
print("Algolia Response Hit title: \(responseHit.object["title"]!)")
但是当我尝试使用以下代码将该值分配给变量时:
self.recipeTitleShort = responseHit.object["title"]
我收到以下错误:
Cannot assign value of type 'JSON?' to type 'String?'
我还尝试了以下方法:
self.recipeTitleShort = responseHit.object["title"] as? String ?? ""
但是变量每次都被赋值
""
。
如何从 JSON 响应中获取该对象字段/值,并将其分配为字符串变量?