Appending to Array in Deeply Nested Dictionary of Arrays - arrays

I am having the following problem in Swift. First, I declare a data structure, like this:
var books = [String : Dictionary<String, Dictionary<String, Dictionary<String, Array<Dictionary<String, String>>>>>]()
I later initialize the var like this:
books = [
"Fiction" : [
"Genre Fiction" : [
"Mystery" : [
"Classics" : [
["Title" : "Ten Little Indians",
"Author" : "Agatha Christie",
"read" : "no"],
["Title" : "A Study in Scarlet",
"Author" : "Arthur Conan Doyle",
"read" : "no"],
]
]
]
]
]
Note that the compiler does not complain about it. Later, I create a new dictionary which I would like to append to that innermost array, like this:
var bookDict = Dictionary<String, String>()
bookDict = ["title" : dict.valueForKey("title") as! String,
"author": dict.valueForKey("author") as! String,
"read" : dict.valueForKey("read") as! String ]
books["category"]["genre"]["focus"]["set"].append(bookDict)
However, I get a compiler error that "Cannot invoke append with an argument list of type (Dictionary < String, String>)". This is confusing to me because the books data structure is declared such that that innermost array is an array of Dictionary< String, String>.
What am I missing?

It's not clear during compile time if the key is really present in the dictionary so dictionaries always return optional values. You have to check this optionals:
if let category = books["Fiction"] {
if let genre = category["Genre Fiction"] {
if let focus = genre["Mystery"] {
if var set = focus["Classics"] {
set.append(bookDict)
}
}
}
}
Or you can do it also like this:
books["Fiction"]?["Genre Fiction"]?["Mystery"]?["Classics"]?.append(bookDict)

Related

How to convert model with array to JSON array Swift 3

i have some question and solution, i have class model and it has array inside, my model like this
class WillModel{
var name: String = ""
var documents:[WillItems] = []
var isLFStatus : Bool = false
var isLFShared : Bool = false
}
class WillItems{
var documentPath: String = ""
var documentRemark: String = ""
}
i want to convert the result to JSON Array like
{
"name" : "value",
"documents" : [
{
"documentPath" : "value"
"documentRemark" : "value"
},
{
"documentPath" : "value2"
"documentRemark" : "value2"
}
],
"isLFStatus" : true,
"isLFShared" : true
}
i'm using Swift 3, thanks for your solutions
You can write a simple method to manually encode your model to json as below,
func encodeWillModel(_ model: WillModel) -> [String: Any] {
var params: [String: Any] = [:]
params["name"] = model.name
params["documents"] = model.documents.map({["documentPath": $0.documentPath,
"documentRemark": $0.documentRemark]})
params["isLFStatus"] = model.isLFStatus
params["isLFShared"] = model.isLFShared
return params
}
and you can pass any model to get the json something like,
let willModelJSON = encodeWillModel(yourModel)
But a better approach would be to use any json parsing library(SwiftyJSON, ObjectMapper) that supports Swift 3 or upgrade to Swift 4 and use Encodable/Decodable

Can we mix types in an array in swift?

In Swift 3 playground, I want to create a mutable array with numbers at some indices and Strings at others. I get errors doing this:
var playerInfo = [[String]]()
playerInfo[0][2] = "Adam" //Error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP, subcode=0x0)
playerInfo[0][3] = "Martinez"
playerInfo[0][1] = "00"
EDIT:
Something like this?
var playerInfo: [[String:Any]] = [
[
"playerNumber" : "00",
"playerFirstName" : "Adam",
"playerLastName" : "Martinez"
]
]
You are not using the syntax correctly.
Try this:
var playerInfo = [[String]]()
playerInfo.append(["00","Adam","Martinez"])
EDIT
For your edit, you need a Dictionary:
var playerInfo = Dictionary<String, Any>()
playerInfo["playerNumber"] = "00"
playerInfo["playerFirstName"] = "Adam"
playerInfo["playerLastName"] = "Martinez"

Why isn't as3 handing my arrays in JSON?

Here I have this json file.
{
"BnUs5hQZkJWLU9jGlpx9Ifq5ocf2" : {
"bio" : "Your bio!\r",
"birthday" : "Date of Birth?",
"location" : "Location?",
"markerBorder" : 1.5542403222038021E7,
"markerColor" : 8222122.31461079,
"name" : "NamesName?",
"profilePrivacy" : 2,
"sex" : "Gender?",
"privacy" : 2,
"points" : {
"-Kc7lfJk3XbPlNyk-wIR" : {
"address" : "dsfsdfasfsfd",
"description" : "status/desription",
"latitude" : 35.2,
"longitude" : -80.7,
"mediaTargets" : "none",
"pub" : false,
"timestamp" : 1486205926658
},
"aaa" : "aaa"
}
}
}
Those random string of charactors are automatically made when I use firebase.
In this scenario, there might be more "points" I will have to take account for. So when I reference points, I should be talking to an array since it contains both "-Kc7lfJk3XbPlNyk-wIR" (an array) and "aaa" (a string).
So why do I get a type error when trying to convert parsedObject.points into an array?
var parsedObject:Object = JSON.parse(e.target.data);
var multiArray:Array = parsedObject.points;
TypeError: Error #1034: Type Coercion failed: cannot convert Object#5c16089 to Array.
I'm basically trying to do the opposite of what this guy is doing.
Edit: I see in the notes that it only handles string, numbers and Boolean values..
I managed to work around it by adding a "parent" node in the object that duplicates the same value as the name of the entire node so I can reference it in the script. Is there a better way to go about this? Seems pretty redundant.
var parsedObject:Object = JSON.parse(e.target.data);
var myPoints:Object = parsedObject["points"];
//Get all trek names
for each (var key:Object in myPoints)
{
trace("Key = " + key.parent);
trace(parsedObject.treks[key.parent].latitude) //Returns -80.7
}
Because Array is a subclass of Object.
var A:Array = new Array();
var B:Object = new Object();
trace(A is Array); // true
trace(A is Object); // true
trace(B is Array); // false
trace(B is Object); // true
B = new Array(); // nothing wrong here
A = new Object(); // throws exception
So, you might want to tell what kind of data you want to obtain in the Array form from the parsedObject.points Object to proceed.
Alternately, that is how you get actual Array from JSON string:
{
"list": [1,2,3,4,5,6]
}
Looks like it's correctly being parsed by JSON.parse to me.
Arrays in JSON use square brackets, braces are interpreted as objects.
You'd only expect an Array from JSON.parse if you had
"points": [
...
]
whereas this is an Object:
"points": {
...
}
I suggest you look into why you aren't getting [] from your source.

How to recreate an array of dictionaries that belong to an alphabet letter?

I am trying to create a new array of objects from an existing array with objects within Swift 3. So I have an array of letters that contain objects that begin with that letter (the name key of that object) so that I can use that new array of dictionaries for the sections within a tableview. What I would like to have is that the first letters of each name key of each object will be examine, than extract the first letter of the name and store it as an array.
For example, a dictionary contains a name like "Lisa". The first letter is L and that one doesn't exists yet. It will create an array for the letter L. Check the next entry. If the next entry starts with an L again, add it to the array with the letter L. If the next one starts with an S, create a new array of S and add it to that array etc etc.
var names = [
[
"name" : "Lisa",
"street" : "Lorem ipsum"
],
[
"name" : "Jeffrey",
"street" : "Lorem ipsum"
],
[
"name" : "Arnold",
"street" : "Lorem ipsum"
],
[
"name" : "Jacob",
"street" : "Lorem ipsum"
],
[
"name" : "Sam",
"street" : "Lorem ipsum"
],
[
"name" : "Anita",
"street" : "Lorem ipsum"
],
[
"name" : "Lotte",
"street" : "Lorem ipsum"
]
]
func createArrarDic(array: [[String: String]]) -> [[String: String]] {
var result = [[String: String]]()
// Loop through array
for object in array {
for (key, value) in object {
let index = value.index(value.startIndex, offsetBy: 1)
let firstLetter = value.substring(to: index).uppercased()
print(firstLetter)
if result[firstLetter] != nil {
result[firstLetter]!.append(object)
} else {
result[firstLetter] = [object]
}
}
}
return result
}
createArrarDic(array: names)
I came up with above code, but it will throw me an error of:
Cannot subscript a value of type '[[String : String]]' with an index of type 'String'
It clear that I do something wrong with the result declaration, but can't figure out how it should be. The check for the first letter should be done in the object, but to reorder and create a new array for each letter it should not be done within that object, but one level above it.
Also the problem is that for(key, value) will examine all the key/value- pairs in that object and I only need the "name" key.
Update
I have came to the following code. I have the return type and the return value to [String: [String: String]]() because of it should start with the letter that contains the object referred to it.
The only problem now is that I don't know how to append an object to the array of a specific letter, because of .append or something like += operator doesn't work. Any thoughts on this one?
func createArrarDic(array: [[String: String]]) -> [String: [String: String]] {
var result = [String: [String: String]]()
// Loop through array
for object in array {
// Loop through dictionaries
for (_, value) in object {
let index = value.index(value.startIndex, offsetBy: 1)
let firstLetter = value.substring(to: index).uppercased()
print(firstLetter)
if result[firstLetter] != nil {
// Append
result[firstLetter]! += object
} else {
result[firstLetter] = object
}
}
}
return result
}
let changedArray = createArrarDic(array: names)
I think this does what you want:
func createArrarDic(array: [[String: String]]) -> [String: [[String: String]]] {
return array.reduce([String: [[String: String]]]()) { result, object in
guard let name = object["name"] else {
return result
}
if name.characters.count == 0 {
return result
}
let firstLetter = String(name[name.startIndex]).uppercased()
var mutableResult = result
if mutableResult[firstLetter] == nil {
mutableResult[firstLetter] = [object]
} else {
mutableResult[firstLetter]?.append(object)
}
return mutableResult
}
}

How to add new value to dictionary [[String : String]]

I have a dictionary, which looks like this:
var dict = [["number" : "1" ], ["number" : "2" ], ["number" : "3" ]]
Now I would like to add new value "level" : "(number of level)" to each index in my dictionary, and it should looks like that:
var dict = [["number" : "1", "level" : "one"], ["number" : "2", "level" : "two" ], ["number" : "3", "level" : "three" ]]
How can I add some value inside existing dictionary in this case?
What you have listed as a dictionary is actually an array of dictionaries. You can add an element to each of the directories by simply iterating the array.
You can use an NSNumberFormatter to convert the digits you have into equivalent words:
var anArray=[["number":"1"],["number":"2"],["number":"3"]]
let numberFormatter=NSNumberFormatter()
numberFormatter.numberStyle=NSNumberFormatterStyle.SpellOutStyle
for i in 0..<anArray.count {
if let numberString=anArray[i]["number"] {
if let number=Int(numberString) {
anArray[i]["level"]=numberFormatter.stringFromNumber(number)
}
}
}
As Paulw11 pointed out, you could use NSNumberFormatter to convert the digits to words:
let dictArray = [["number" : "1" ], ["number" : "2" ], ["number" : "3" ]]
let numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = NSNumberFormatterStyle.SpellOutStyle
let mappedDictArray = dictArray.map { var d = $0; d["level"] = numberFormatter.stringFromNumber(number); return d; }
However, if you're interested in using the level key only for UI purposes, you'd be better writing a Dictionary extension, as there's no point is storing a redundant value:
extension Dictionary {
func levelString() -> String {
let numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = NSNumberFormatterStyle.SpellOutStyle
return numberFormatter.stringFromNumber(self["number"] as? Int ?? 0)
}
}
which can be used like this:
dictArray[0].level()

Resources