Swift:flatMap to Dictionary
发布时间:2020-12-14 04:41:33 所属栏目:百科 来源:网络整理
导读:我试图解析以下 JSON: { "String For Key 1": [ "Some String A","Some String B","Some String C",],"String For Key 2": [ "Some String D","Some String E","Some String F" ],"String For Key 3": [ "Some String G","Some String H","Some String I","
我试图解析以下
JSON:
{ "String For Key 1": [ "Some String A","Some String B","Some String C",],"String For Key 2": [ "Some String D","Some String E","Some String F" ],"String For Key 3": [ "Some String G","Some String H","Some String I","String For Key 4": [ "Some String J","Some String K","Some String L" ],"String For Key 5": [ "Some String M","Some String N","Some String O" ],"String For Key 6": [ "Some String P","Some String Q","Some String R" ] } 我也关注这个tutorial.它在Playground的Github上 在示例中,他们使用typealias JSONDictionary = [String:AnyObject]解析字典数组 我需要解析一个具有Key的字典,这个字符串是String,而Value是一个Array.因此:typealias JSONDictionary = [String:[AnyObject]],我在返回flatMap时遇到错误. extension Resource { init(url: NSURL,parseJSON: AnyObject -> A?) { self.url = url self.parse = { data in let json = try? NSJSONSerialization.JSONObjectWithData(data,options: []) as? [String: [AnyObject]] //This is where I get an error return json.flatMap(parseJSON) } } } 错误: Cannot convert value of type `AnyObject -> A? to expected argument type `([String: [AnyObject]]?) -> _? 如何获得一个字符串,字符串为String,值为数组?我想保留他们的通用方法. 解决方法
jsonString的类型是Dictionary< String,Array< String>>
你可以给它一个像Dictionary< String,AnyObject>这样的类型. AnyObject可以包含类和结构,即Array,Dictionary,String,Int,Obj C Classes let jsonString:[String: AnyObject] = [ "String For Key 1": [ "http://www.urlToSomePathA.jpg","http://www.urlToSomePathB.jpg","http://www.urlToSomePathC.jpg","String For Key 2": [ "http://www.urlToSomePathD.jpg","http://www.urlToSomePathE.jpg","http://www.urlToSomePathF.jpg" ] ] // Now you can map a function on the value type let values = jsonString.flatMap { $0.1 as? [String] } print(values) // RESULT: [["http://www.urlToSomePathA.jpg","http://www.urlToSomePathC.jpg"],["http://www.urlToSomePathD.jpg","http://www.urlToSomePathF.jpg"]] 更新 let keys = jsonString.flatMap { $0.0 } // ["String For Key 1","String For Key 2"] 正如@dffri所评论的那样,你可以在字典上使用keys属性,它将返回LazyMapCollection,只有当你访问里面的对象时才会实现. let keys = jsonString.keys (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |