Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 908
Pippo Avatar asked Jan 10 '17 21:01

Pippo


2 Answers

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.

like image 120
Ahmad F Avatar answered Sep 19 '22 15:09

Ahmad F


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"]
]
like image 25
Ronan Avatar answered Sep 23 '22 15:09

Ronan