How store items of a dictionary to another dictionary with a key in swift?

问题内容:

I got a dictionary say dict1 with some keys and values and i want to store all the values of dict1 to another dictionary say dict2 with a key and i tried parse them to JSON using SwiftyJson.
What i tried has been given below,

var dict1 = [String: String]()
var dict2 = [String: String]()

// Values of dict1
dict1["details"] = "XXXXX"

//trying to save values of dict1 to dict2
dict2["moreDetails"] = dict1 as? String
let jsonValue = JSON(dict2)
print(jsonValue)

What i obtain is an empty jsonString like this { }

What i actually want to get is

{
"moreDetails" :{
         "details" : "XXXXX"
      }
}

How could i achieve the above

问题评论:

2  
try this :- var Dict2 = [String: Any]()

答案:

答案1:

As AshvinGudaliya’s comment suggests, the issue is the type of dict2 – you’ve typed it as [String: String], and then you try to put an object of type [String: String] as a value – but it will only accept String values.

Creating dict2 as a [String: Any] will allow you to add a non-string value to it, in this case the contents of dict1, a [String: String]

答案评论:

原文地址:

https://stackoverflow.com/questions/47713462/how-store-items-of-a-dictionary-to-another-dictionary-with-a-key-in-swift

添加评论

友情链接:蝴蝶教程