简体   繁体   English

Swift for-in循环字典实验

[英]Swift for-in loop dictionary experiment

I'm almost a complete programming beginner and I've started to go through a Swift ebook from Apple. 我几乎是一个完整的编程初学者,我已经开始通过Apple的Swift电子书。

The things I read are pretty clear, but once you start to experiment things get tricky :). 我读到的东西很清楚,但是一旦你开始尝试,事情变得棘手:)。

I'm stuck with the experiment in the Control Flow section. 我坚持在控制流程部分进行实验。 Here is the initial code: 这是初始代码:

let interestingNumbers = [
    "Prime": [2, 3, 5, 7, 11, 13],
    "Fibonacci": [1, 1, 2, 3, 5, 8],
    "Square": [1, 4, 9, 16, 25],
]

var largest = 0
for (kind, numbers) in interestingNumbers {
    for number in numbers {
        if number > largest {
            largest = number
        }
    }
}

largest

And here is the task: 这是任务:

Add another variable to keep track of which kind of number was the largest, as well as what that largest number was. 添加另一个变量以跟踪哪个数字最大,以及最大数量是多少。

As I understand, they want me to add up all the values in each number kind (get a total sum for Prime, Fibonacci and Square) and then compare the result to show the largest result. 据我了解,他们希望我将每个数字类型的所有值相加(得到Prime,Fibonacci和Square的总和),然后比较结果以显示最大的结果。 But I can't figure out the syntax. 但我无法弄清楚语法。

Can someone share any advice on how to tackle this experiment? 有人可以就如何解决这个实验分享任何建议吗? Maybe I'm not understanding the problem? 也许我不明白这个问题?

They're just asking you to keep track of which number category the largest number belongs to: 他们只是要求您跟踪最大数字所属的数字类别:

let interestingNumbers = [
    "Prime": [2, 3, 5, 7, 11, 13],
    "Fibonacci": [1, 1, 2, 3, 5, 8],
    "Square": [1, 4, 9, 16, 25],
]
var largest = 0
var largestkind = ""
for (kind, numbers) in interestingNumbers {
    for number in numbers {
        if number > largest {
            largest = number
            largestkind = kind
        }
    }
}
largest
largestkind

Alternately you can use closure to make the tasks simpler. 或者,您可以使用闭包来简化任务。

The for loop calculate the sum of each series. for循环计算每个系列的总和。

The final reduce finds the series tuple that contains maximum number. 最终的reduce查找包含最大数字的系列元组。

let interestingNumbers = [
    "Prime": [2, 3, 5, 7, 11, 13],
    "Fibonacci": [1, 1, 2, 3, 5, 8],
    "Square": [1, 4, 9, 16, 25],
]

var sums =  Array<(String, Int)>()
for (kind, numbers) in interestingNumbers {
    sums = sums + [(kind, numbers.reduce(0, +))]
}

let maxSeries = sums.reduce(("", Int.min), { $0.1 > $1.1 ? $0 : $1 })

println(sums)
println(maxSeries)

Here it from playground using Xcode 8.3 and Swift 3.0 这是来自使用Xcode 8.3和Swift 3.0的游乐场

let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]

let largest = interestingNumbers.map{$0.value}.flatMap{$0}.max()
print(largest)

Optional(25) 可选(25)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM