Fastest way to parse text from an array - arrays

I am trying to parse an array of items, each of which is structured like below:
[0x6100000b2480 - Message: Phlare, ID: 92329382, Sender: 2077303954, Timestamp: 1505263276721]
But I am just trying to get the value after "Sender:" so in this case "2077303954". But I will be iterating through a list of these, parsing the value out of each array index.

Assuming "," only appears between values, separate them into pieces using split:
let arr = str.characters.split(separator: ",").map(String.init)
println(arr) // [0x6100000b2480 - Message: Phlare, ID: 92329382, Sender: 2077303954]
You can then split the strings in the resulting array again on ":" to get an array of alternating keys values.
Or perhaps the input was already an array?
Here's an example:
var resultingDictionary = [String:String]()
var stringArray = ["0x6100000b2480 - Message: Phlare", "ID: 92329382", "Sender: 2077303954", "Timestamp: 1505263276721:"]
for eachString in stringArray
{
let arr = eachString.characters.split(separator: ":").map(String.init)
resultingDictionary[arr[0]] = arr[1]
}
print("resulting dictionary is \(resultingDictionary)")
The same concept should work with NSString's componentsSeparatedByString (now known as components(separatedBy: ",").

Related

Sort an object array [Venue] by its property using a sorted array [Geofire Keys] as reference?

I have built the following "helper" function, which takes as parameters:
'unsortedArray': The array of Venue objects required to be sorted by its .venueID string property
'sortingGeoArray': the Geofire string keys to be used as reference to order the unsorted array above.
and it returns a sorted array of type [Venue] via an escaping handler.
I have tried to implement this nice and simple solution suggested on the following thread:
'Sorting a Swift array by ordering from another array'
func sortVenuesArraybyGeofireKeys(unsortedArray: [Venue], sortingGeoArray: [String] , handler: #escaping (_ sortedArray: [Venue]) -> ()){
let ordering = Dictionary(uniqueKeysWithValues: sortingGeoArray.enumerated().map { ($1, $0) })
let sorted: [Venue] = unsortedArray.sorted{ ordering[$0.venueID]! < ordering[$1.venueID]! }
handler(sorted)
}
I have tried the sorting code above in multiple places through out my code by I always get a "Unexpectedly found nil while unwrapping an Optional value" at the following line (works when i test it an playground):
let sorted: [Venue] = unsortedArray.sorted{ ordering[$0.venueID]! < ordering[$1.venueID]!
On my debug window below, I have a feeling that the .map function into the let 'ordering' is not working and therefore finding nil on the next line
any help would be appreciated.
UPDATE: thanks to the support below, it appears that my Geofire query below in particular the 'append' to venueGeoKeys [string] array is not appending the key values, hence why found nil when I execute the function to sort.
let query = self.GEOFIRE_VENUES.query(at: location, withRadius: 1000)
query.observe(.keyEntered) { (key: String!, location: CLLocation!) in
self.venueGeoKeys.append(key)
}

Swift 3: Dictionary from large arrays

I am working with two large arrays containing following data:
print(dataID[1]) // ["DataID123"]
print(dataAR[1]) // ["73.075584"]
I'd like to form a dictionary from the two arrays by:
var arrayofDict = [String: AnyObject?]()
for i in 0...csvDataID.count {
if i < csvDataID.count {
let key = csvDataID[i]
let value = csvDataAG[i]
arrayofDict[key] = value
}
}
But get following error:
Cannot subscript a value to '[String: AnyObject?]' with an index of
type '[String]'
I also tried a few other approaches aswell resulting in the same error.
Could anyone help me and is there even a more efficient way to handle the arrays?
Thanks!
let key = csvDataID[i][0]
let value = csvDataAG[i][0]
Explaination:
The log says that csvDataID[1] is an array: ["DataID123"]
The same is for the second one.:["73.075584"]
So,
let key = csvDataID[i] // you set the key is array.
That's why you can see this error.

Reading data from cvs file and converting data into multidimensional array in Swift

I'm new to Swift. I can read data (many rows and columns of names and mailing addresses) from csv file format. I have several of these files, so I created a function just to read the files and extract the data into a multidimensional array(s) - names, addresses, city, state, country. I read each of the lines from the file and try to append it to multidimensional array but I get errors - either index out of range or file type mismatch. What's the best way to enable this. See code below.
func getMailing(fileName: String) -> ([[String]])? {
let totalList = 243
var tempList: [String] = []
var arrayList = [[String]]()
guard let path = Bundle.main.url(forResource: fileName, withExtension: "csv") else {
print("File Error")
arrayList = [[""]]
return (arrayList)
}
do {
// get mailing data from file
let content = try String(contentsOf:path, encoding: String.Encoding.utf8)
// separate each line entry
tempList = content.components(separatedBy: "\r\n")
for index in 0...totalList - 1 {
// get each line from list and post into an array
let singleLine = tempList[index].components(separatedBy: ",").dropFirst().prefix(5)
// store each line data into into a multidimensional array for easy retrieval
arrayList[index].append(singleLine)
}
}
return (arrayList)
} catch {
print("File Error")
arrayList = [[""]]
return (arrayList)
}
}
Based on the code you've shown, it looks like you're trying to change the values of two different empty arrays 243 times. You have a loop setup to iterate based on your totalList property, but where you got that value, I have no idea. It would be wise to determine that value programmatically if you can.
You're setting both tempList and arrayList as empty arrays:
var tempList: [String] = []
var arrayList = [[String]]()
But then you're going through a loop and trying to change the value of an entry that doesn't even exist, hence your index out of range error. You need to first add something to both these arrays, because right now they are empty. It's probably crashing the first time through the loop when you try to set singleLine to tempList[index].components(separatedBy: ",").dropFirst().prefix(5), because you're saying tempList[0].components(separatedBy: ",").dropFirst().prefix(5), while there isn't an entry for tempList at index 0 because it's still empty! If you're going to loop through an array, it's always wise to do it based on the count of the array, or at least a quick fix when you need to use an index from two different arrays:
// Get the maximum times you can iterate based on the lowest count from each array
let maxLoop = min(tempList.count - 1, arrayList.count - 1)
for index in 0...maxLoop {
// get each line from list and post into an array
let singleLine = tempList[index].components(separatedBy: ",").dropFirst().prefix(5)
// store each line data into into a multidimensional array for easy retrieval
arrayList[index].append(singleLine)
}
Now that little chunk of code above won't even go through the loop once, because both arrays are still empty. You need to somewhere take your mailing data and parse it so that you can populate tempList and arrayList

swift - using .map on struct array

i have a struct array that i want "break up" into smaller arrays that can be called as needed or at least figure out how i can map the items needed off one text value.
the struct:
struct CollectionStruct {
var name : String
var description : String
var title : String
var image : PFFile
var id: String
}
and the array made from the struct
var collectionArray = [CollectionStruct]()
var i = 0
for item in collectionArray {
print(collectionArray[i].name)
i += 1
}
printing partArray[i].name gives the following result:
pk00_pt01
pk00_pt02
pk00_pt03
pk01_pt01
pk01_pt02
pk01_pt03
pk01_pt04
pk01_pt05
pk01_pt06
pk01_pt07
pk01_pt08
this is just some test values but there could be thousands of entries here so i wanted to filter the entire array just by the first 4 characters of [i].name i can achieve this by looping through as above but is this achievable using something like .map?
I wanted to filter the entire array just by the first 4 characters of
[i].name
You can achieve this by filtering the array based on the substring value of the name, as follows:
let filteredArray = collectionArray.filter {
$0.name.substring(to: $0.name.index($0.name.startIndex, offsetBy: 4)).lowercased() == "pk00"
// or instead of "pk00", add the first 4 characters you want to compare
}
filteredArray will be filled based on what is the compared string.
Hope this helped.
If you want to group all data automatically by their name prefix. You could use a reducer to generate a dictionary of grouped items. Something like this:
let groupedData = array.reduce([String: [String]]()) { (dictionary, myStruct) in
let grouper = myStruct.name.substring(to: myStruct.name.index(myStruct.name.startIndex, offsetBy: 4))
var newDictionart = dictionary
if let collectionStructs = newDictionart[grouper] {
newDictionart[grouper] = collectionStructs + [myStruct.name]
} else {
newDictionart[grouper] = [myStruct.name]
}
return newDictionart
}
This will produce a dictionary like this:
[
"pk00": ["pk00_pt01", "pk00_pt02", "pk00_pt03"],
"pk01": ["pk01_pt01", "pk01_pt02", "pk01_pt03", "pk01_pt04", "pk01_pt05", "pk01_pt06", "pk01_pt07"],
"pk02": ["pk02_pt08"]
]
Not sure if i am understanding you correctly but it sounds like you are looking for this...
To create a new array named partArray from an already existing array named collectionArray (that is of type CollectionStruct) you would do...
var partArray = collectionArray.map{$0.name}

Comparing two arrays in swift, with different lengths

I want to compare two arrays with each other and append the value that is not in the other array to a new array. The problem now is that all of the values that does not equal the other array already get appended, but I want only the values that are new in the other array getting appended.
I hope that the problem is clear. Sorry if it's a very vague question. I try to be clear haha.
The code and output is printed below:
// Iterate through all possible values
for i in 0...messages.count-1{
var match = false
for r in 0...self.messages.count-1{
println("NIEUWE" + messages[i].getID() + "OUDE" + self.messages[r].getID())
if(messages[i].getID().toInt() == self.messages[r].getID().toInt()){
var match = true
println(match)
break
}
}
if (!match) {
newArray.append(messages[i])
println(newArray)
}
}
Output:
NIEUWE170OUDE170
NIEUWE170OUDE171
true
[PostDuif.Message]
NIEUWE171OUDE170
true
[PostDuif.Message, PostDuif.Message]
NIEUWE172OUDE170
true
This "I want to compare two arrays with each other and append the value that is not in the other array to a new array" is just 'set difference'
var s1 = Set(["a", "b", "c"]) // this to be similar to your need
var s2 = Set(["b", "c", "d"])
var s3 = s2.subtract (s1)
As such:
9> var s3 = s2.subtract(s1)
s3: Set<String> = {
[0] = "d"
}
Note that you have subtract, intersect, and union with inPlace options as methods on the Set type. New to Swift 1.2.

Resources