【问题标题】:Check if the returned value is an integer if so return string in Swift检查返回值是否为整数,如果是,则在 Swift 中返回字符串
【发布时间】:2026-02-08 13:20:05
【问题描述】:

我正在使用 Algolia Search 接收数据列表(点击)。

我得到一个像下面这样的单元格参数;

cell.textLabel?.text = [String: Any](hit)?["im_code"] as? String

但是,这可能会返回一个字符串或一个 int。我想将其强制为字符串。我试图将它包装在一个字符串中,但它不起作用。

附加说明

不幸的是,Algolia 的后端不允许您对值进行类型转换,因此它不是后端的选项。

型号说明

[String: Any](hit)?["im_code"] 可以返回 IntString。我需要这个总是被强制串起来。

【问题讨论】:

  • 你的代码应该显示String或nil,而不是IntString?,这很奇怪,为什么你说显示IntString?,实际上是@987654330 @ 是String? 类型属性
  • 如果返回值是一个 int 我需要把它作为字符串

标签: swift string int algolia


【解决方案1】:

您可以将类型转换为通用协议CustomStringConvertibledescription 属性返回字符串表示:

let value = hit?["im_code"] as? CustomStringConvertible ?? ""
cell.textLabel?.text = value.description

【讨论】:

  • 这会将 int 作为双精度值返回。
  • 那么你的IntDouble
【解决方案2】:

这里有几个选项:

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)"

【讨论】:

  • 让 value = [String: Any](hit)?["im_code"] if let value = value as? String { cell.textLabel?.text = value } else if let value = value as? Int { cell.textLabel?.text = String(value) } 返回 nil
最近更新 更多