Swift-从字典中读取不同类型的值

时间:2019-06-20 06:53:17

标签: swift string dictionary

目前我所拥有的代码正在将所有值读取为String。但是,当存在整数或十进制值时,它将被读取为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”仅适用于String,因此替换出现的内容时出现错误。

因此,我检查了res对象的类,如果它不是String,我尝试执行以下操作,但是由于res的类型为AnyObject,并且由于不存在而出现错误,因此尝试将其替换为空字符串。

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

2 个答案:

答案 0 :(得分:1)

StringIntDouble有一种常见类型:CustomStringConvertible

视情况将值向下转换为CustomStringConvertible并使用String Interpolation获得字符串

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

答案 1 :(得分:0)

您应该将“获取字典值”部分和“将其转换为我想要的类型”部分分开。然后,您应该使用if let语句检查从字典中获得的值的类型。

let value = dict[fieldName.uppercased()] ?? dict[fieldName.lowercased()]

if let string = value as? String {
    url = url.replacingOccurrences(of: testString, with: string.addingPercentEncoding(withAllowedCharacters: allowedCharSet) ?? "")
} else if let double = value as? Double {
    url = url.replacingOccurrences(of: testString, with: "\(double)".addingPercentEncoding(withAllowedCharacters: allowedCharSet) ?? "")
} else if let integer = value as? Int {
    url = url.replacingOccurrences(of: testString, with: "\(integer)".addingPercentEncoding(withAllowedCharacters: allowedCharSet) ?? "")
} else {
    // value is nil, or is none of the types above. You decide what you want to do here
}