Convert Any dictionary array to String in Swift - ios

Convert [String:Any] dictionary array to [String:String] in Swift
I have an array of dictionary <String,Any> type. Now I want to convert to string because I want to show data in textField and text field not understand Any data type.
My data like this:
var myarr = [[String:Any]]()
[
[
"Area" : "",
"Good" : "-",
"Level" : 2,
"Link" : "<null>",
"Photo" : "-",
"Repair" : "-",
"Section" : "Others"
],
[
"Area" : "",
"Good" : "N",
"Level" : 2,
"Link" : "http://google.com",
"Photo" : 1,
"Repair" : "Y",
"Section" : "Grounds"
]
]
and I want new Array Dictionary:
var myarr = [[String:String]]()

Map is your friend, maybe something like
let stringDictionaries: [[String: String]] = myarr.map { dictionary in
var dict: [String: String] = [:]
dictionary.forEach { (key, value) in dict[key] = "\(value)" }
return dict
}

Here is one solution that actually gives the correct results:
let myarr = [
[
"Area" : "",
"Good" : "-",
"Level" : 2,
"Link" : "<null>",
"Photo" : "-",
"Repair" : "-",
"Section" : "Others"
],
[
"Area" : "",
"Good" : "N",
"Level" : 2,
"Link" : "http://someurl",
"Photo" : 1,
"Repair" : "Y",
"Section" : "Grounds"
]
]
var newarr = [[String:String]]()
for dict in myarr {
var newdict = [String:String]()
for (key, value) in dict {
newdict[key] = "\(value)"
}
newarr.append(newdict)
}
print(newarr)
Output:
[["Level": "2", "Area": "", "Good": "-", "Link": "<null>", "Repair": "-", "Photo": "-", "Section": "Others"], ["Level": "2", "Area": "", "Good": "N", "Link": "http://someurl", "Repair": "Y", "Photo": "1", "Section": "Grounds"]]

You can create new dictionary using following code:
var newArray:[[String: String]] = []
for data in myarr {
var dict: [String: String] = [:]
for (key, value) in data {
let strData = String(describing: value)
dict[key] = strData
}
newArray.append(dict)
}

Related

Find Scalable solution to print data from Array in Swift

I have an array starting from 1 to 100 and I have to print element if the number is divisible by 4 it should print the letter "A" and if the number is divisible by 5 it should print the letter "B" and if it is divisible by both then "AB" I want to make a scalable solution if in future I want to add number divisible by 8 should print "C" and divisible by 4 & 8 should print "AC", by 5&8 should print "BC" and if all three then "ABC"
desired output:
1
2
3
A
B
6
7
C
9
B
11
AB
13
14
...
I wrote this
for number in 1...100 {
if number.isMultiple(of: 4) && !number.isMultiple(of: 5){
print("A"
} else if !number.isMultiple(of: 4) && number.isMultiple(of: 5){
print("B")
} else if number.isMultiple(of: 4) && number.isMultiple(of: 5){
print("AB")
} else {
print(number)
}
}
Please provide a scalable solution to keep adding If-else is not a good option.
You were pretty close but you don't need the else conditions. Just add the character to the string if it matches another condition:
for number in 1...100 {
var string = ""
if number.isMultiple(of: 4) { string.append("A") }
if number.isMultiple(of: 5) { string.append("B") }
if number.isMultiple(of: 8) { string.append("C") }
print(string.isEmpty ? number : string)
}
Using a dictionary to store the characters:
let dict = [
4: "A",
5: "B",
8: "C"
]
for number in 1...100 {
var string = ""
for (key, character) in dict where number.isMultiple(of: key) {
string.append(character)
}
print(string.isEmpty ? number : string)
}
Note that dictionary is an unordered collection. If you need the characters to be sorted you would need to sort the dictionary by its values before iterating its key value pairs:
let sortedDict = dict.sorted(by: { $0.value < $1.value })
for number in 1...100 {
var string = ""
for (key, character) in sortedDict where number.isMultiple(of: key) {
string.append(character)
}
print(string.isEmpty ? number : string)
}
Here it is, instead of using if-else, you can just add up whenever you need
var stringArray = [String]()
for number in 0...100 {
stringArray.append(String(number))
}
// stringArray = ["0","1", "2", "3",....,"99", "100"]
// Adding a zero before to compare with the index
stringArray = stringArray.enumerated().map({ index, item in
var value = item
if index % 4 == 0 {
value = Int(item) == nil ? item + "A": "A"
}
return value
})
stringArray = stringArray.enumerated().map({ index, item in
var value = item
if index % 5 == 0 {
value = Int(item) == nil ? item + "B": "B"
}
return value
})
stringArray = stringArray.enumerated().map({ index, item in
var value = item
if index % 8 == 0 {
value = Int(item) == nil ? item + "C": "C"
}
return value
})
stringArray.removeFirst()
print(stringArray)
Result::
"1", "2", "3", "A", "B", "6", "7", "AC", "9", "B", "11", "A", "13", "14", "B", "AC", "17", "18", "19", "AB", "21", "22", "23", "AC", "B", "26", "27", "A", "29", "B", "31", "AC", "33", "34", "B", "A", "37", "38", "39", "ABC", "41", "42", "43", "A", "B", "46", "47", "AC", "49", "B", "51", "A", "53", "54", "B", "AC", "57", "58", "59", "AB", "61", "62", "63", "AC", "B", "66", "67", "A", "69", "B", "71", "AC", "73", "74", "B", "A", "77", "78", "79", "ABC", "81", "82", "83", "A", "B", "86", "87", "AC", "89", "B", "91", "A", "93", "94", "B", "AC", "97", "98", "99", "AB"
if you just want [Any] type then just
var resultArray = [Any]()
resultArray = stringArray.map({ number in
if let num = Int(number) { return num }
else { return number }
})
print(resultArray)

How to group array of objects with same key value pair

I have an array of dictionaries with same key value pairs.
[
{ "amount": "10" },
{ "amount": "20" },
{ "amount": "30" },
{ "amount": "20" },
{ "amount": "10" },
{ "amount": "10" }
]
I need to group this based on same key values.
Expected sample result:
There are 3x 10's, 2x 20's and 1x 30's
How do I achieve this?
let array = [ ["amount": "10"], ["amount": "20"], ["amount": "30"], ["amount": "20"], ["amount": "10"], ["amount": "10"] ]
var result: [String: Int] = [:]
let key = "amount"
array.forEach {
guard let value = $0[key] else { return }
result[value, default: 0] += 1
}
print("\(result["10"])") // 3

Array of dictionary comparision - swift3

I have 2 array of dictionaries. I want to write a function which compare these 2 arrays.
Function should return true only if main array contains sub array element.
Else it should return false.
Here is my logic-
let mainArry = [ ["id":"1","products":["pid": 1, "name": "A", "price": "$5"]], ["id":"3","products":["pid": 3, "name": "B", "price": "$1"]], ["id":"2","products":["pid": 14, "name": "C", "price": "$15"]]]
let array1 = [ ["id":"1","products":["pid": 1, "name": "A", "price": "$5"]], ["id":"3","products":["pid": 3, "name": "B", "price": "$1"]]]
let array2 = [ ["id":"1","products":["pid": 1, "name": "A", "price": "$5"]], ["id":"3","products":["pid": 4, "name": "B", "price": "$1"]]]
func compareDictionary(mainArry:[[String: Any]], arr2: [[String: Any]])-> Bool{
let itemsId = arr2.map { $0["id"]! } // 1, 3, 14
let filterPredicate = NSPredicate(format: "id IN %#", itemsId)
let filteredArray = mainArry.filter{filterPredicate.evaluate(with:$0) }
if filteredArray.count != arr2.count {
return false
}
for obj in filteredArray {
let prd = obj as Dictionary<String, Any>
let str = prd["id"] as! String
let searchPredicate = NSPredicate(format: "id == %#", str )
let filteredArr = arr2.filter{searchPredicate.evaluate(with:$0) }
if filteredArr.isEmpty {
return false
}
if !NSDictionary(dictionary: obj["products"] as! Dictionary<String, Any>).isEqual(to: filteredArr.last!["products"] as! [String : Any]) {
return false
}
}
return true
}
let result1 = compareDictionary(mainArry: mainArry, arr2: array1)
let result2 = compareDictionary(mainArry: mainArry, arr2: array2)
print("Result1 = \(result1)") // true
print("Result2 = \(result2)") //false
It is working. But I want to know the best way to achieve this.
Instead of using for-loop for comparision.
I want to use filter like this
let arrayC = filteredArray.filter{
let dict = $0
return !arr2.contains{ dict == $0 }
}
if arrayC is empty that means both arrays are equal.
I got it Finally!
We don't need to write big function.
let mainArry = [ ["id":"1","products":["pid": 1, "name": "A", "price": "$5"]], ["id":"3","products":["pid": 3, "name": "B", "price": "$1"]], ["id":"2","products":["pid": 14, "name": "C", "price": "$15"]]]
let array1 = [ ["id":"1","products":["pid": 1, "name": "A", "price": "$5"]], ["id":"3","products":["pid": 3, "name": "B", "price": "$1"]]]
let array2 = [ ["id":"1","products":["pid": 1, "name": "A", "price": "$5"]], ["id":"3","products":["pid": 4, "name": "B", "price": "$1"]]]
let result = array2.filter{
let dict = $0
return !mainArry.contains{
return NSDictionary(dictionary: dict).isEqual(to: $0)
}
}
if result.isEmpty {
print("Same key values")
} else {
print("Diff key values")
}

swift 4 split array and filter

i will build a UICollectionView with sections.
The sections are based on the return value from json.category.
the json format is like:
[{"id":"1",
"name":"Apple",
"category":"Fruits"},
{"id":"2",
"name":"Pie",
"category":"Fruits"},
{"id":"3",
"name":"Tomato",
"category":"Vegetable"}]
I need a array filter hat the array is something like: (for sectionsItems and sectionNames)
CategorieNames[STRING] = ["Fruits","Vegetable"] // the section names from json.category
Fruits = [STRING] = ["Apple","Pie"]
Vegetables = [STRING] = ["Tomato"]
Categories.append[Fruits]
Categories.append[Vegetables]
Categories[[STRING]] = [[Fruits],[Vegetable]]
Try bellow code.
let arrData = [["id": "1",
"name": "Apple",
"category": "Fruit"],
["id": "2",
"name": "Pie",
"category": "Fruit"],
["id": "3",
"name": "Tomato",
"category": "Vegetable"]]
let categorieNames = Array(Set(arrData.map({$0["category"]!})))
var arrResult:[[String]] = []
for i in 0..<categorieNames.count {
let categories = arrData.filter({$0["category"] == categorieNames[i]}).map({$0["name"]!})
arrResult.append(categories)
}
print("result : \(arrResult)")
result : [["Apple", "Pie"], ["Tomato"]]
you can do it as follows:
let arrData = [["id": "1",
"name": "Apple",
"category": "Fruit"],
["id": "2",
"name": "Pie",
"category": "Fruit"],
["id": "3",
"name": "Tomato",
"category": "Vegetable"]]
var categorys = [[String]]()
var fruits = [String]()
var vegetable = [String]()
for data in arrData {
if let category = data["category"] {
if category == "Fruit"{
if let aFruit = data["name"] {
fruits.append(aFruit)
}
}
else if category == "Vegetable" {
if let aVeggeie = data["name"] {
vegetable.append(aVeggeie)
}
}
}
}
categorys.append(fruits)
categorys.append(vegetable)

how to add sub array in main array in swift

{
"firstName": "AA",
"lastName": "BB,
"shortName": "CC",
"nric": "12/AAA(N)123456",
"gender": "F",
"dob": "1.1.2000",
"password": "admin123",
"photo": {
"image": "hello",
"thumb": "world"
}
}
Is there anyway how to add photo array in main array? I've done as follow
let photoArray = [
"image": imageBase64,
"thumb": imageBase64
]
let param = [
"firstName": txtFirstName.text as! AnyObject,
"lastName": txtLastName.text as! AnyObject,
"shortName": txtShortName.text as! AnyObject,
"nric":"",
"gender": genderCode,
"dob":txtDOB.text as! AnyObject,
"photo": photoArray
]
but output is awful. Please let me how to do it.
Instead of making the param let make it var and do the following. You do need to specify the dictionary type as below
let photoArray : [String : AnyObject] = [
"pic" : "myPhoto"
]
var param : [String : AnyObject] = [
"name" : "UserName"
]
param["photo"] = photoArray
let photoArray = [[
"image": "a",
"thumb": "b"],[
"image": "a",
"thumb": "b"]
]
let param = [
"firstName": txtFirstName.text as! AnyObject,
"lastName": txtLastName.text as! AnyObject,
"shortName": txtShortName.text as! AnyObject,
"nric":"",
"gender": genderCode,
"dob":txtDOB.text as! AnyObject,
"photo": photoArray
]
Hope you want like this.
let photoArray:[String:UIImage] = [
"image": UIImage.init(named: "a.png")!,
"thumb": UIImage.init(named: "b.png")!
]
let param:[String:AnyObject] = [
"firstName": "AA",
"lastName": "BB",
"shortName": "CC",
"nric": "",
"gender": 0,
"dob": "DD",
"photo": photoArray
]
You can do it like this

Resources