首页 > 解决方案 > Swift - 从字典中读取不同类型的值

问题描述

目前,我拥有的代码正在将所有值读取为字符串。但是,有时存在整数或十进制值时,它会被读取为 nil。

现在的代码:

let fieldName = String(arr[0])
var res = dict[fieldName.uppercased()] as? String
if res == nil {
   res = dict[fieldName.lowercased()] as? String
}
url = url.replacingOccurrences(of: testString, with: res?.addingPercentEncoding(withAllowedCharacters: allowedCharSet) ?? "")

有时“dict[fieldName.uppercased()]”返回值,例如 3 或 40.4,但我的 res 对象中的值是 nil,因为我期待一个字符串。

如何读取不同类型的值并更新我的 url 中的出现?

我试过的代码:

let fieldName = String(arr[0])
var res = dict[fieldName.uppercased()] as? AnyObject
if res == nil {
   res = dict[fieldName.lowercased()] as? AnyObject
}
url = url.replacingOccurrences(of: testString, with: res?.addingPercentEncoding(withAllowedCharacters: allowedCharSet) ?? "")

有了这个,我在替换事件时遇到错误,因为“addingPercentEncoding”仅适用于字符串。

所以我检查 res 对象的类,如果它不是字符串,我尝试执行以下操作,但是由于 res 是 AnyObject 类型而出现错误,如果不存在,我尝试用空字符串替换它。

url = url.replacingOccurrences(of: testString, with: res ?? "" as String)

标签: swiftstringdictionary

解决方案


和有一种常见的类型StringIntDoubleCustomStringConvertible

有条件地将值向下转换为CustomStringConvertible并使用字符串插值获取字符串

let fieldName = String(arr[0])
if let stringConvertible = dict[fieldName.uppercased()] as? CustomStringConvertible {
    url = url.replacingOccurrences(of: testString, with: "\(stringConvertible)".addingPercentEncoding(withAllowedCharacters: allowedCharSet
}

推荐阅读