HotDudeSmith - 1 year ago 121

Swift Question

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

`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

Answer Source

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
}
}[1]
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
}.0
print(result1)
print(result2)
```

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.