我试图从不同数字序列的字典中获取最大和最大的。
var largest = 0
var largestKind: String?
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
if largestKind != kind {
largestKind = kind
}
}
}
}
largest
largestKind
如果之前的largestKind值不是同一个,我只想设置maximumKind。我知道这样做几乎没用,但我只是想更好地了解一下Swift。我尝试使用带有let的if语句,但我无法使用条件。
提前感谢您的帮助。
答案 0 :(得分:0)
您可以使用Optional Binding
从可选项中获取值for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
if let oldLargestKind = largestKind {
if oldLargestKind != kind {
largestKind = kind
}
}
else {
// largestKind was nil
largestKind = kind
}
}
}
}
当然,如果您只是分配它,它会更干净并且仍然可以工作:
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
largestKind = kind
}
}
}
当然,如果你真的想深入了解Swift,这是另一个实现:
let (largest, largestKind) = reduce(interestingNumbers, (num: 0, kind: nil)) {
(largest: (num: Int, kind: String?), next: (kind: String, numbers: [Int])) in
func maxNumInArray(array: [Int]) -> Int {
return array.reduce(0, combine: max)
}
var localLargest = maxNumInArray(next.numbers)
return localLargest > largest.num ? (localLargest, next.kind) : largest
}
从可理解性的角度来看,这实际上更糟糕,但它在Swift中展示了一些更高级的功能:
编辑:要在最后访问maximumKind的解包值:
if let actualLargestKind = largestKind {
// In here you have access to the value stored in
// largestKind under the name of actualLargestKind
doSomethingWithTheLargestKind(actualLargestKind)
}