这是一些代码:
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/