在苹果Swift的循环 [英] For Loop in Apple Swift

查看:124
本文介绍了在苹果Swift的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

苹果新发布的语言Swift在官方文档。例如这样;

Apple's newly released language Swift has an example on the official documentation. Example is like this;

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

这是非常简单的,但作为一个额外的练习,它需要添加另一个变量才能返回什么类型是最大的数字(即这里的正方形)

This is pretty simple but as an extra exercise,it requires to add another variable in order to return what type is the largest number (i.e. Square is the case here)

然而,我似乎无法弄清楚这里代表什么是(种类,数字),我应该如何让我的循环遍历所有的Dictionary(interestingNumbers)键并找到哪个键有最大的数字。

However, I can't seem to figure out what is "(kind,numbers)" here represent and how should I make my for-loop to go through all Dictionary(interestingNumbers) keys and find which key has the largest number.

提前谢谢大家的帮助

推荐答案

Swift允许您使用 tuple-syntax (key,value)循环使用字典。所以在For循环Swift的每一次迭代中都关心重新分配指定的元组变量( kind 数字在你的案例)到实际的字典记录。

Swift allows you to loop over a dictionary with tuple-syntax (key, value). So in every iteration of the for-loop Swift cares about reassigning the specified tuple-variables (kind and number in your case) to the actual dictionary-record.

要弄清楚哪个键包含您的示例中最高的数字,您可以按如下方式扩展代码:

To figure out which Key includes the highest number in your example you can extend your code as follows:

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 largestKey = ""
for (kind, numbers) in interestingNumbers {
    for number in numbers {
        if number > largest {
            largest = number
            largestKey = kind
        }
    }
}
largest     // =25
largestKey  // ="Square"

或者如果要练习元组语法,请尝试(具有相同的结果):

Or if you want to practice the tuple-syntax try that (with the same result):

var largest = 0
var largestKey = ""
for (kind, numbers) in interestingNumbers {
    for number in numbers {
        if number > largest {
            (largestKey, largest) = (kind, number)
        }
    }
}
largest     // =25
largestKey  // ="Square"

这篇关于在苹果Swift的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆