How to parse json correctly in ios? - ios

For example I need to get all english "text" values of "ex" scope from JSON example
What I do:
let result = json["def"].arrayValue.map({ $0["tr"].arrayValue.map { $0["ex"] } })
but at as a result I got a double massive and if I intend to get all "text" then I will get a triple array. Guess should be another more elegant approach to this task. Is anyone can show a really good solution?

If your expression gives 3 arrays of Strings you could add .reduce([], +) at the end to join the 3 arrays into
one.
EDIT:
I was typing from memory, and said the wrong thing. You would use reduce, not joined.
let result = json["def"]
.arrayValue
.map({ $0["tr"].arrayValue.map { $0["ex"] } })
.reduce([], +)
That should give you what you want.
EDIT #2:
The reduce function operates on sequences (like arrays). It takes an "initial result" value that seeds the process, and then a closure that operates on 2 elements, and returns a result. (a "binary" closure)
The + operator is actually a binary closure in Swift. It takes 2 elements and returns a single result, so you can simply pass in + instead of a closure. For arrays, + returns the result of combining the arrays.
So when you use reduce() on an array of arrays, and [] as the initial result, it combines [] with the first array, then the result of each + operator with the next entry in the array.
Take this simplified code for example:
//Start with an array of arrays of strings
let arrays = [
["string1", "string2", "string3"],
["string4", "string5", "string6"],
["string7", "string8", "string9"]
]
//First loop through the outer arrays and log their contents
for (index, object) in arrays.enumerated() {
print("array[\(index)] = \(object)")
}
//Now combine the outer arrays into a single array
let combined = arrays.reduce([], + )
//Now print the entries in the combined array
print("\n---- combined arrays ----")
for (index, object) in combined.enumerated() {
print("array[\(index)] = \(object)")
}
That produces the following output:
array[0] = ["string1", "string2", "string3"]
array[1] = ["string4", "string5", "string6"]
array[2] = ["string7", "string8", "string9"]
---- combined arrays ----
array[0] = string1
array[1] = string2
array[2] = string3
array[3] = string4
array[4] = string5
array[5] = string6
array[6] = string7
array[7] = string8
array[8] = string9

Related

Compare the elements in the array to see if there are duplicates in the string

Currently, I'm having a problem comparing an array with a string. I have 2 arrays and want to find out if the elements in those 2 arrays are in the string
let resultString = "STEREON10.000 4ailthameGrinreD NOCHIMINNICHNUÖC-LOINHÀ GIAIDACBIET2ty UnOMMOSTCRShitConDONG FlimChineCrJ045 Dòketquásoan: XSHCM goi 7181 8186-8110°593364THUBAY6A7 05-6-2021teIntaiKNInTaiChínhTP.HCM"
let code_province:[String] = ["xsag", "xsbd", "xsbdi", "xsbl","xsbp",
"xsbt", "xsbth", "xscm", "xsct", "xsdl",
"xsdlk", "xsdn", "xsdng", "xsdno", "xsdt",
"xsgl", "xshcm", "xshg", "xskg", "xskh",
"xskt", "xsla", "xsmb", "xsnt", "xspy",
"xsqb", "xsqng", "xsqnm", "xsqt", "xsst",
"xstg", "xstn", "xstth", "xstv", "xsvl",
"xsvt", "xsbri",]
let name_Province:[String] = ["angiang","binhduong","binhdinh","baclieu", "binhphuoc","bentre", "binhthuan", "camau", "cantho", "dalat","daklak", "dongnai", "daNang", "daknong", "dongthap","gialai", "hcm", "haugiang", "kiengiang", "khanhhoa","kontum", "longan", "mienbac", "ninhthuan", "phuyen","quangbinh", "quangNgai", "quangnam", "quangtri", "soctrang","tiengiang", "tayninh", "thuat.hue", "travinh", "vinhlong","vungtau","baria"]
Here is one way:
let f: (String) -> String? = { resultString.localizedStandardContains($0) ? $0 : nil }
let provincesInResult = code_province.compactMap(f)
let namesInResult = name_Province.compactMap(f)
We map the list of things to search for from a list of strings, to nil if not found and the string if found. Then we compact the result to leave us with just a list of the found ones. That may be 0, 1 or more, so consider those possibilities.

Create a team generator with a given number of teams

I would like to take an array of [String] and split it up into a given number of groups.
I have tried using this extension
extension Array {
func chunked(into size: Int) -> [[Element]] {
return stride(from: 0, to:count, by: size).map {
Array(self[$0 ..< Swift.min($0 + size, count)])
}
}
}
to split the array into a given number of elements per subarray, which for that function it works.
But to split it into a desired number of subarrays, I tried dividing the array.count by the desired number of teams, which works but only in certain circumstances.
If there are any extra elements, it puts them into an extra subarray at the end, and the number needs to come out even if I want this to work perfectly, which is the minority of the time.
So I guess this array.chunked function is not the solution in any way.
Maybe there is a way to do it with a for loop by taking an array.randomElement(), adding that to a variable (which would be a team) and then removing that element from the original array, and iterating over it until the original array is empty. And end up with an array of subarrays which would be the teams, or just separate variables which would be the teams. It could be any of those options.
Any ideas on how to do this?
Think about how you deal cards.
If you have 7 players, you start with one player and go around, giving one card at a time to each player. At the end, you may run out of cards before giving everybody the same number of cards. Some people may have n cards, and some may have n-1. That's the best that you can do.
You could implement the same thing with a source array and your destination arrays. Remove one element at a time from the source array, and "round-robbin" add it to one of the destination arrays until the source array is exhausted.
That code might look like this:
func splitArray<T>(array: [T], subArrayCount: Int) -> [[T]] {
// Create an empty array of arrays
var result = [[T]]()
// Create the empty inner string arrays
for _ in 1...subArrayCount {
let innerArray = [T]()
result.append(innerArray)
}
for (index, element) in array.enumerated() {
result[index % subArrayCount].append(element)
}
return result
}
And to test it:
let string = "Now is the time for all good programmers to babble incoherently. The rain in spain falls mainly on the plain. Fourscore and seven years ago our forefathers brought forth to this continent a new nation conceived in liberty and dedicated to the cause that all men are created equal."
let array = string.split(separator: " ")
.map { String($0) }
let subArrays: [[String]] = splitArray(array: array, subArrayCount: 5)
for (index, array) in subArrays.enumerated() {
let countString = String(format: "%2d", array.count)
print ("Array[\(index)]. Count = \(countString). Contents = \(array)")
}
The output of that test is:
Array[0]. Count = 10. Contents = ["Now", "all", "incoherently.", "falls", "Fourscore", "our", "this", "conceived", "to", "men"]
Array[1]. Count = 10. Contents = ["is", "good", "The", "mainly", "and", "forefathers", "continent", "in", "the", "are"]
Array[2]. Count = 10. Contents = ["the", "programmers", "rain", "on", "seven", "brought", "a", "liberty", "cause", "created"]
Array[3]. Count = 10. Contents = ["time", "to", "in", "the", "years", "forth", "new", "and", "that", "equal."]
Array[4]. Count = 9. Contents = ["for", "babble", "spain", "plain.", "ago", "to", "nation", "dedicated", "all"]

how to store values in a 1D array into a 2D array in Swift 4

Hi I would like to store values of a 1D array into a 2D array.
My 1D array has 50 elements and I want to store it in a 5x10 array, but whenever I do that, it always gives me a "Index out of range" error
Any help would be appreciated thanks!
var info2d = [[String]]()
var dataArray = outputdata.components(separatedBy: ";")
for j in 0...10 {
for i in 0...5 {
info2d[i][j] = dataArray[(j)*5+i]
print(info2d[i][j])
}
}
Lots of error in your code.
info2d must be initialised with default values before using it by index
// initialising 2d array with empty string value
var info2d = [[String]](repeating: [String](repeating: "", count: 10), count: 5)
Secondly for loop with ... includes the last value too, use ..<
for j in 0..<10 {
//...
}
Thirdly (j)*5+i is incorrect too.
Better Read how to use arrays, collections and for loop in swift.
https://docs.swift.org/swift-book/LanguageGuide/ControlFlow.html
https://docs.swift.org/swift-book/LanguageGuide/CollectionTypes.html
I would make use of ArraySlice for this.
var arr2D = [[String]]()
for i in 0..<5 {
let start = i * 10
let end = start + 10
let slice = dataArray[start..<end] //Create an ArraySlice
arr2D.append(Array(slice)) //Create new Array from ArraySlice
}

How to add a text prefix to an array on Swift?

Right now I have a array that when printed just displays what number I submitted. I would like the word "car" to be in front of every array number. For example: I enter 1 and 2 in the array. When the array is called it would look like [car 1, car 2] not [1,2].
I have added my array variable and what I am calling to print the array:
var arrayOfInt = [Int]()
label.text = String(describing: arrayOfInt)
Try this:
let arrayOfInt: [Int] = [1, 2]
let cars = arrayOfInt.map { "car \($0)" }
as a result, the cars array will be:
["car 1", "car 2"]
finally, convert to string as before:
label.text = String(describing: cars)
The Array.map function returns an array containing the results of mapping the given closure over the array's elements. In other words, it tranforms one array into another one by applying the specified function on each element.

substring with an array string - Swift

I have an array:
var array = ["1|First", "2|Second", "3|Third"]
How I can cut off "1|", "2|", "3|"?
The result should look like this:
println(newarray) //["First", "Second", "Third"]
You can use (assuming the strings will contain the "|" character):
let newarray = array.map { $0.componentsSeparatedByString("|")[1] }
As #Grimxn pointed out, if you cannot assume that the "|" character will always be in the strings, use:
let newarray = array.map { $0.componentsSeparatedByString("|").last! }
or
let newarray2 = array.map { $0.substringFromIndex(advance(find($0, "|")!, 1)) }
result2 could be a little bit faster, because it doesn't create an intermediate array from componentsSeparatedByString.
or if you want to modify the original array:
for index in 0..<array.count {
array[index] = array[index].substringFromIndex(advance(find(array[index], "|")!, 1))
}

Resources