迭代NSDictionary中的字符串数组

时间:2017-02-11 06:22:05

标签: swift swift3

我有一个从解析JSON获得的NSDictionary。其中一个对象是字符串数组。我怎么能遍历这个数组?我完全纠结于正确地投射一切 - 我尝试的每件事都会引发投射错误。例如。 (许多不同尝试之一)

if let answers = myDict.object(forKey: "answers") as? Array {
    for answer in answers {
        let answerString: String = answer as! String
        //do something with the string
    }
}

throws“String”不能转换为“Any”

2 个答案:

答案 0 :(得分:2)

假设它已被解析为字典中的字符串数组,您应该能够这样做:

if let answers = myDict["answers"] as? [String] {
  for answer in answers {
    // Do something with answer (which is a String)
  }
}

答案 1 :(得分:0)

let ans = myDict["answers"]
if ans is [String] {
let answers = ans as! [String]
   for answer in answers {
       // Do something with answer (which is a String)
   }
}