HotDudeSmith HotDudeSmith - 4 months ago 23
Swift Question

Swift - How to find max or min element in Dictionary and Two-dimensional Array in Array list

I am trying to find out what to write the code for this specific two examples in Swift for finding max or min element in Dictionary with Array and Two-dimensional Array in Array list.

Example #1 - Find max element in Two-dimensional Array

let myArray = [["A_1", "1"], ["A_2", "0"], ["A_3", "25"], ["A_4", "3"]]
print(myArray.maxElement()!) // <--- it doesn't work properly

Output: 25

Example #2 - Which key has (highest items count) max element in Dictionary with Array

let myList = [("A_1", [["C", "C"]]), ("A_2", [["A", "A"], ["B", "B"], ["C", "C"]]), ("A_3", [])]

.... //Trying to figure it out what kind of code to add here...

Output: A_2 //has 3 items in array


There are lots of way to write this, here's one:

let myArray = [["A_1", 1], ["A_2", 0], ["A_3", 25], ["A_4", 3]]
let result1 = myArray.reduce(myArray.first!) { aggregate, element in
    if let aggregateValue = aggregate[1] as? Int,
        let elementValue = element[1] as? Int where aggregateValue < elementValue {
        return element
    } else {
        return aggregate

let myList = [("A_1", [["C", "C"]]), ("A_2", [["A", "A"], ["B", "B"], ["C", "C"]]), ("A_3", [])]
let result2 = myList.reduce(myList.first!) { aggregate, element in
    aggregate.1.count < element.1.count ? element : aggregate


Basically reduce starts with a seed value (the first element of each array), then iterate through the array to determine which is the max overall.