【问题标题】:How to get tuple values into a dictionary by using parameters of a function in swift如何通过在swift中使用函数的参数将元组值放入字典中
【发布时间】:2018-04-16 12:36:05
【问题描述】:

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

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

【问题讨论】:

  • 如果您发布代码将非常有帮助。
  • 我可以在几个小时内完成。目前在工作,但吃过午饭,想在我回家之前提前发帖。或者在此之前我可能有时间手工完成
  • Class YearlyTemps { var Months: [String] var Temperatures: [String,(temp1: Int, temp2: Int)] = [:] func SetMonthlyTemps(month: String, temp1: Int, temp2: Int) -> Void { //jumbled mess here that I can't figure how to populate dictionary } func ShowResult() -> Void { //wrong print here as I am not using a key yet } } 很抱歉评论中的混乱,但手机在这里很烂
  • 为了将来参考,请编辑您的问题并在此处添加代码,而不是将其放入评论中。
  • 我试过了,但是把代码放到手机上是很可怕的。天啊。我把它全部输入了,但由于缩进有 4 个空格,它一直拒绝我的编辑,但我什至检查了它,但仍然被拒绝。

标签: arrays swift dictionary tuples swift-playground


【解决方案1】:

享受:

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

【讨论】:

  • 哇塞字典这么容易?现在我只需要弄清楚如何使用月份数组作为键来调用它!由于您无法对字典进行排序
【解决方案2】:

从我的角度来看,如果您使用的是受限数据集,例如月、周、类别,我不知道那么最好使用 enum 来更好地描述您的数据,而不是元组和字符串

enum Month {
  case january
  case february
//  ...
  case november
  case december

  static let allMonths = [january, february, /*...*/ november, december]
}

struct MonthlyTemperature {
  let month: Month
  var lowestTemp: Double?
  var highestTemp: Double?

  init(month: Month, lowest: Double? = nil, highest: Double? = nil) {
    self.month = month
    self.lowestTemp = lowest
    self.highestTemp = highest
  }
}

let temparatures = [MonthlyTemperature]()
// ...
var dict = Dictionary(grouping: temparatures, by: { $0.month })

Month.allMonths.forEach { month in
  dict.updateValue(dict[month] ?? [], forKey: month)
}

【讨论】:

  • 我确信这很好用,但我必须为这个目标使用某些对象和函数
  • @Noobprogrammer626 它比元组更灵活和更具装饰性
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-31
  • 1970-01-01
相关资源
最近更新 更多