简体   繁体   English

如何从字典中打印一些键Swift

[英]How print some keys from a dictionary Swift

I'm experimenting with a little bit of code, this is what I want: I want to print the keys from a dictionary but only if this keys have a value more than 10. This is my code: 我正在尝试一些代码,这就是我想要的:我想从字典中打印键,但前提是该键的值必须大于10。这是我的代码:

var alumnos = ["jose": 20, "leo": 56, "hadad": 8]

In this case only "jose" and "leo" have to be printed, because their values are more than 10. 在这种情况下,仅必须打印“ jose”和“ leo”,因为它们的值大于10。

Have you tried something like this: 您是否尝试过以下方法:

for (key, value) in alumnos {
   if value > 10 {
      print(key)
   }
}

You can also turn it into a function like so: 您也可以将其转换为如下功能:

func printKeyForValueGreaterThan10<T: Hashable>(dict: [T: Int]) {
  for (key, value) in dict {
    if value > 10 {
      print(key)
    }
  }
}

And call it by passing your dictionary. 并通过您的字典来称呼它。

printKeyForValueGreaterThan10(dict: alumnos)

You can obtain the keys of interest using higher-level functions: 您可以使用更高级的功能来获取感兴趣的键:

let keysOfValuesAboveTen = alumnos.filter {$0.1 > 10}.map {$0.0}

You can make a string with a separator from it like this: 您可以像这样用分隔符创建一个字符串:

let str = alumnos.filter {$0.1 > 10}.map {$0.0}.joinWithSeparator(", ")

这是解决此问题的最基本方法:

for (stringKey, intValue) in alumnos { if intValue > 10 { print(stringKey) } }

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

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