2017-06-18 30 views
2

这里的价值是一些代码:抓斗从字典<String, Any>斯威夫特卡伦特3

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

这就是“迪科”这是从赛格瑞来:

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

我想要得到它们各自的价值'dico'的元素作为一个字符串重复使用后作为一个长字符串(这是一个地址为Geocoder) 任何人都知道?

由于我有这个错误以前的代码:

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

回答

1

尝试串插的这个组合,可选链接条件铸造零合并运算??

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 ?? "")" 
+0

我不明白这些是什么? “”但它现在工作完美。非常感谢你 ! – BenoHiT

+0

* nil合并运算符*'??'展开一个可选项,如果它不为零,并且它为零,则它使用提供的默认值'“”'。无论哪种情况,您最终都会获得一个非可选项,并且不会崩溃。 – vacawama

+0

aaah好吧,我明白了!谢谢你的解释,赞赏 – BenoHiT