arrays - Reduce a string to a dictionary in Swift -
what woudl simple way reduce string aaa:111;bbb:222;333;444;ccc:555 dictionary in swift. have following code:
var str = "aaa:111;bbb:222;333;444;ccc:555" var astr = str.componentsseparatedbystring(";").map { (element) -> [string:string] in var elements = element.componentsseparatedbystring(":") if elements.count < 2 { elements.insert("n/a", atindex: 0) } return [elements[0]:elements[1]] }
code above produces array of dictionaries:
[["a": "111"], ["bbb": "222"], ["ukw": "333"], ["ukw": "444"], ["ccc": "555"]]
i want produce
["a": "111", "bbb": "222", "ukw": "333", "ukw": "444", "ccc": "555"]
no mater try, since call map function on array seems impossible convert nature of map function's result.
note: dictionary in string format described either having key:value; format or value; format, in case mapping function add "n/a" being key of unnamed value.
any on matter appreciated.
your map produces array of dictionaries. when want combine them 1, that's perfect job reduce:
func + <k,v>(lhs: dictionary<k,v>, rhs: dictionary<k,v>) -> dictionary<k,v> { var result = dictionary<k,v>() (key, value) in lhs { result[key] = value } (key, value) in rhs { result[key] = value } return result } var str = "aaa:111;bbb:222;333;444;ccc:555" var astr = str .componentsseparatedbystring(";") .reduce([string: string]()) { aggregate, element in var elements = element.componentsseparatedbystring(":") if elements.count < 2 { elements.insert("n/a", atindex: 0) } return aggregate + [elements[0]:elements[1]] } print(astr) swift has no default operator "combine" 2 dictionaries have define one. note + here not commutative: dicta + dictb != dictb + dicta. if key exist in both dictionaries, value second dictionary used.
Comments
Post a Comment