我是IOS的新手, 我从后端得到了这个回复
Optional([["contact_name": phone, "verified": <null>, "id": 22033, "entity_id": 1111, "verification_data": <null>, "entity": Recruiter, "view_scope": <null>, "contact_value": 0987654321]])
我需要&#34; contact_value&#34;来自object的字符串。我怎么得到?
答案 0 :(得分:4)
而不是正常的for循环,try map concept。 注意:这是经过测试的代码。
let arrayOfDict: [[String: Any]] = [["contact_name": "phone", "verified": "", "id": 22033, "entity_id": 1111, "verification_data": "", "entity": "Recruiter", "view_scope": "", "contact_value": 0987654321]]
let arraOfCtcName : [Int] = arrayOfDict.map({ (element) in
let value = element["contact_value"]
return (value != nil && value is Int) ? value as! Int : 0
})
答案 1 :(得分:3)
let array: [[String: Any]] = [["contact_name": "John", "verified": true, "id": 22033, "entity_id": 1111, "verification_data": "", "entity": "Recruiter", "view_scope": "", "contact_value": 0987654321]]
for item in array {
let contactName = item["contact_name"] as? String
print(contactName ?? 0)
}
这只是提取数据的基本/循环,但是根据代码的实现方式,有很多更好的方法可以完成这些工作。
答案 2 :(得分:1)
如果您想要的只是contact_value,
,您可以更加实用let contactValues = a.flatMap { $0 }?
.map { $0["contact_value"] ?? 0 } as? [Int]
答案 3 :(得分:0)
let arrayOfDict: [[[String: Any]] = ["contact_name": "phone", "verified": <null value>, "id": 22033, "entity_id": 1111, "verification_data": <null value>, "entity": "Recruiter", "view_scope": <null value>, "contact_value": 0987654321], ....]
var arrayContact = [Any]()
for dict in arrayOfDict {
if let contactValue = dict["contact_value"] as? String { //as String
arrayContact.append(contactValue)
} else if let contactValue = dict["contact_value"] as? Int { //as Int
arrayContact.append(contactValue)
}
}
print(arrayContact)
答案 4 :(得分:0)
let array: [[String: Any]] = [["contact_name": "John", "verified": true, "id": 22033, "entity_id": 1111, "verification_data": "", "entity": "Recruiter", "view_scope": "", "contact_value": 0987654321]]
print(array)
for item in array {
if item["contact_value"] != nil {
let contact_value = String(describing: item["contact_value"])
print(contact_value)
break
}
}
答案 5 :(得分:-3)
可选([[&#34; contact_name&#34 ;: phone,&#34;已验证&#34;:,&#34; id&#34;:22033,&#34; entity_id&#34;:1111, &#34; verification_data&#34;:,&#34; entity&#34 ;: Recruiter,&#34; view_scope&#34;:,&#34; contact_value&#34;:0987654321]])
var string = Optional.toString()