gpt4 book ai didi

arrays - 如何使用 swift 中函数的参数将元组值放入字典中

转载 作者:行者123 更新时间:2023-11-30 12:02:01 25 4
gpt4 key购买 nike

我的目标是使用 Playground 并显示每月温度(例如,一月高温为 30,低温为 -2),它需要使用字符串数组以及包含温度元组值的字典.

到目前为止,我有一个字符串数组Months: [String],其中包含月份。以及温度字典:[String, (temp1: Int, temp2: Int)。我有一个函数 SetMonthlyTemp(month: String, temp1: Int, temp2: Int) 我试图用它来设置字典,但我不知道如何做到这一点。我对字典完全陌生,上周只使用过一次元组,那是作为一个独立的属性。任何有关设置此字典以获取元组 (Int, Int) 的帮助都会很棒!显然会有一个显示方法来打印结果,但我在查找信息方面没有任何问题。

最佳答案

享受:

var temperatures = [String: (Int, Int)]()
temperatures["Jan"] = (10, 20)
temperatures["Feb"] = (-1, -16)
// setting temp 1 for January (note: "Jan" entry must exist in dictionary)
temperatures["Jan"]?.0 = 30

// setter ;)
func setMonthlyTemp(month: String, temp1: Int, temp2: Int) {
temperatures[month] = (temp1, temp2)
}

访问:

temperatures["Feb"]      // whole tuple for February
temperatures["Jan"]?.0 // first temperature for January
temperatures["Feb"]?.1 // second temperature for February

关于arrays - 如何使用 swift 中函数的参数将元组值放入字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47101521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com