Ios Swift 3是否迭代嵌套字典?
好的,那么,斯威夫特·努布警报: 给定以下数组(我不知道该怎么称呼这个形状:数组、字典、对象…),我如何进行最简单的迭代 发件人[“操作”]: 可选([{“文本”:“确认”,“类型”:“响应”},{“文本”:“拒绝”,“类型”:“响应”},{“链接”:”https://www.stackoverflow.com“,”文本“:”网站“,”类型“:”信息“}]) 尝试:Ios Swift 3是否迭代嵌套字典?,ios,swift,loops,Ios,Swift,Loops,好的,那么,斯威夫特·努布警报: 给定以下数组(我不知道该怎么称呼这个形状:数组、字典、对象…),我如何进行最简单的迭代 发件人[“操作”]: 可选([{“文本”:“确认”,“类型”:“响应”},{“文本”:“拒绝”,“类型”:“响应”},{“链接”:”https://www.stackoverflow.com“,”文本“:”网站“,”类型“:”信息“}]) 尝试: if let result = sender["actions"] { print("YES \(result)") fo
if let result = sender["actions"] {
print("YES \(result)")
for action in result as! [String] {
print(action)
}
}
以上打印内容
:
YES [{"text":"Confirm","type":"response"},{"text":"Decline","type":"response"},{"link":"https:\/\/www.stackoverflow.com","text":"Website","type":"info"}]
…但是,返回以下错误:
无法将类型为“\uu NSCFString”(0x1a7c28d50)的值强制转换为“NSArray”(0x1a7c297c8)
这里的最终目标是简单地单独完成每一项操作,即:
{“text”:“Confirm”,“type”:“response”}
{“文本”:“拒绝”,“键入”:“响应”
等等
Swift是否有map
功能…仅供参考,我来自Java和JavaScript世界…swiftyjson
对于一个循环来说似乎有点沉重
谢谢,一如既往,我们感谢您的帮助和指导
编辑:
这是通过传递给函数发送器的参数进行的打印:
sender: [AnyHashable("title"): title!, AnyHashable("message"): message, AnyHashable("message_id"): 0:1503511875428318%03300c3203300c32, AnyHashable("id"): 1497708240713, AnyHashable("actions"): [{"text":"Confirm","type":"response"},{"text":"Decline","type":"response"},{"link":"https:\/\/www.notifyd.com","text":"Website","type":"info"}], AnyHashable("aps"): {
"content-available" = 1;
}]
您希望解码JSON字符串,然后将其转换为字典数组:
if
// cast sender["actions"] to String
let actionsString = sender["actions"] as? String,
// decode data of string and then cast to Array<Dictionary<String, String>>
let actionsStringData = actionsString.data(using: .utf8),
let result = try JSONSerialization.jsonObject(with: actionsStringData, options: []) as? [[String : String]]
{
print("YES \(result)")
for action in result {
print(action)
}
}
if
//将发件人[“操作”]强制转换为字符串
将actionsString=sender[“actions”]设为?字符串,
//解码字符串的数据,然后将其转换为数组
让actionsStringData=actionsString.data(使用:.utf8),
让result=try JSONSerialization.jsonObject(使用:actionsStringData,选项:[])作为?[[String:String]]
{
打印(“是\(结果)”)
结果如何{
印刷(行动)
}
}
您在这里得到的是一个未编码的JSON字符串,这是真的吗?在这种情况下,Swift 4让这变得非常简单:
struct S : Decodable {
let link : String?
let text : String
let type : String
}
if let acts = sender["actions"] as? String {
let data = acts.data(using: .utf8)!
if let arr = try? JSONDecoder().decode(Array<S>.self, from: data) {
arr.forEach {print($0)}
}
}
/*
S(link: nil, text: "Confirm", type: "response")
S(link: nil, text: "Decline", type: "response")
S(link: Optional("https://www.stackoverflow.com"), text: "Website", type: "info")
*/
structs:Decodable{
让链接:字符串?
让文本:字符串
let类型:String
}
如果让acts=发送方[“操作”]作为?字符串{
让data=acts.data(使用:.utf8)!
如果让arr=try?JSONDecoder().decode(Array.self,from:data){
arr.forEach{print($0)}
}
}
/*
S(链接:无,文本:“确认”,键入:“响应”)
S(链接:无,文本:“拒绝”,类型:“响应”)
S(链接:可选)https://www.stackoverflow.com),文本:“网站”,键入:“信息”)
*/
数据有点可疑。让我们更加小心地对待数据。下面是一个从JSON对象、JSON数组、数据对象或字符串获取JSON的方法
enum JsonError: Error { case notJson; case notJsonArray }
func json(from any: Any?) throws -> Any {
if let json = any as? [String: Any] { return json }
if let json = any as? [Any] { return json }
if let data = any as? Data {
return try JSONSerialization.jsonObject(with: data)
}
if let string = any as? String, let data = string.data(using: .utf8) {
return try JSONSerialization.jsonObject(with: data)
}
throw JsonError.notJson
}
现在我对JSON对象更加小心了,我应该得到我想要的信息,或者知道更多关于错误的信息
func showNotification(_ sender: [AnyHashable: Any]) {
do {
guard let result = try json(from: sender["actions"]) as? [Any] else {
throw JsonError.notJsonArray
}
print("YES \(result)")
for action in result {
print("Action: \(action)")
}
} catch {
// Do Something
}
}
Swift没有地图。这个问题令人困惑。请清楚地显示打印的输出(“YES\(结果)”)
。错误意味着结果
实际上是一个字符串
,这就是为什么不能将其转换为数组。但是您声称的输出来自打印
表明结果
是一个字典数组。这就是为什么我要求您澄清打印
的输出。不,这不是实际的打印因为您的print
语句包含文本YES
。请将print
语句的确切实际输出输入到您的问题中。在我看来,发件人[“actions”]包含JSON字符串,而不是[[string:string]].JSON解码需要进行。如果let
两次,则无需执行操作。如果let result=sender[“actions”]as?[[String:String]
这似乎是正确的(最后)除非它没有解释错误消息。问题中假定的输出意味着这个答案是正确的,但错误消息表明结果
实际上是一个字符串
,而不是一个字典数组。这个问题似乎是矛盾的。@dj-tech42感谢这个片段,不幸的是,使用它并没有命中“是的”,所以没有打印任何内容。我可以发布什么来帮助解决这个问题?我听到矛盾和困惑,但这些形容词并不能引导我找到更好的解决方案,否则也没有帮助。问题是sender[“actions”]
实际上是一个尚未解码的json字符串,因此类型实际上是string
。一旦解码,它将具有类型[[string:string]]
您可以这样强制转换,但如果不解码,此强制转换将失败,并且if
块中的代码将无法运行。这看起来比替代方法更干净。不幸的是,这是一个react本机应用程序,我不相信本机模块部分(swift)将在3以上得到支持(不过我还没有把这当作事实来研究)。
func showNotification(_ sender: [AnyHashable: Any]) {
do {
guard let result = try json(from: sender["actions"]) as? [Any] else {
throw JsonError.notJsonArray
}
print("YES \(result)")
for action in result {
print("Action: \(action)")
}
} catch {
// Do Something
}
}