ios - 从 Swift 3 中的 Dictionary<String, Any> 中获取值

标签 ios swift dictionary

这是一些代码:

class MapViewController: UIViewController {
    var dico:Dictionary<String, Any>?

    override func viewDidLoad() {
        super.viewDidLoad()
        let dest = "\(String(describing: self.dico?.index(forKey: "adresse"))) \(String(describing: self.dico?.index(forKey: "cp"))) \(String(describing: self.dico?.index(forKey: "ville")))"
        print(dest)}}

这是 'dico',它来自一个 segue:

["cp": 1000, "id": 4, "loyer": , "ville": bruxelles, "nom": , "ref": garage2, "adresse": 50 rue de spa, "prenom": , "nouveau_loyer": ]

我想获取 'dico' 的每个元素的值作为一个字符串,以便在作为一个长字符串之后重用它们(它是地理编码器的地址) 有谁知道 ?

使用之前的代码我遇到了这个错误:

Optional(Swift.Dictionary.Index(_value: Swift.DictionaryIndexRepresentation._native(Swift._NativeDictionaryIndex(offset: 13))))

最佳答案

尝试这种字符串插值可选链接条件转换nil合并运算符的组合 ??:

let dest = "\(dico?["adresse"] as? String ?? "") \(dico?["cp"] as? String ?? "") \(dico?["ville"] as? String ?? "")"

如果键 "cp" 的值真的是一个 Int,那么这样做:

let dest = "\(dico?["adresse"] as? String ?? "") \(dico?["cp"] as? Int ?? 0) \(dico?["ville"] as? String ?? "")"

关于ios - 从 Swift 3 中的 Dictionary<String, Any> 中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44617916/

相关文章:

python - 如何创建递归函数将多级字典对象打印到文件

python - 正确地从嵌套字典中获取数据,必须有更好的方法

ios - 这个字符串是什么格式?

ios - 关闭模态视图 Controller 在(iOS13.5 Xcode 11.5)中显示黑屏

ios - Facebook NSArray 问题

swift - 在 Swift 中初始化二维用户定义数组

xcode - 为什么 swift 中的 self 有时颜色不同?

c# - 如何在 C# 中找出字典值的并集?

ios - ios降低应用程序加载时间

android - 移动设备上的图像处理速度