我试图找出在Swift中为这个特定的两个例子编写代码的内容,用于在Array中使用Array和二维数组在Array列表中查找max或min元素。
示例#1 - 在二维数组中查找最大元素
let myArray = [["A_1", "1"], ["A_2", "0"], ["A_3", "25"], ["A_4", "3"]]
print(myArray.maxElement()!) // <--- it doesn't work properly
Output: 25
示例#2 - 具有数组的字典中哪个键具有(最高项目数)最大元素
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
答案 0 :(得分:1)
有很多方法可以写这个,这是一个:
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)
基本上reduce
以种子值(每个数组的第一个元素)开头,然后遍历数组以确定哪个是最大值。
答案 1 :(得分:0)
我为你的例子#1找到了一个很好的例子。也许你可以改变一个更好的东西。但@CodeDifferent提供的是一个非常好的例子。你可以看到我发现的这个例子:
Swift - How to find Largest value from an array and identify which array it came from
我以为你想看到它。