我正在使用Algolia搜索来接收数据列表。 (点击数)
我得到如下所示的单元格参数;
cell.textLabel?.text = [String: Any](hit)?["im_code"] as? String
但是,这可能返回字符串或整数。我想将其强制为字符串。我试图将其包装成字符串,但没有用。
任何帮助都将不胜感激。
不幸的是,Algolias后端不允许您强制转换值,因此后端不提供此选项。
[String: Any](hit)?["im_code"]
可以返回Int
或String
。
我需要始终将其强制为字符串。
答案 0 :(得分:1)
您可以将类型强制转换为通用协议CustomStringConvertible
,description
属性返回字符串表示形式:
let value = hit?["im_code"] as? CustomStringConvertible ?? ""
cell.textLabel?.text = value.description
答案 1 :(得分:0)
您在这里有一些选择:
let value = yourDict?["im_code"] // Assuming Any? as the type
好人
if let value = value as? String {
cell.textLabel?.text = value
} else if let value = value as? Int {
cell.textLabel?.text = String(value)
}
坏人
if let value = value {
cell.textLabel?.text = "\(value)"
}
丑陋
let text: Any = (value as? String) ?? (value as? Int) ?? ""
cell.textLabel?.text = "\(text)"