遍历字典并检查每个值类型

Looping through a dictionary and checking each value type

如何遍历字典并检查每个项目的 value 类型?

示例字典:

var dict = ([
    "a number" : 1,
    "a boolean" : false,
    "a string" : "Hello"
])

我检查值的尝试:

for item in dict.1 {
    if let current = item as? NSNumber {
        print(current)
    }
}

我试过这个:

for item in settings {
    if item[1] == item[1] as NSNumber {
        print(item)
    }
}

重要提示:

正如@Leo 指出的那样,在比较时跟踪字典的值类型 很重要。我作为示例包含的字典的类型为 [String : NSObject],我项目中的字典的类型为 [String : NSNumber]。必须以不同的方式对待他们!

来自 swift 参考,这里是如何遍历字典

Iterating Over a Dictionary

You can iterate over the key-value pairs in a dictionary with a for-in loop. Each item in the dictionary is returned as a (key, value) tuple, and you can decompose the tuple’s members into temporary constants or variables as part of the iteration:

for (airportCode, airportName) in airports {
        println("\(airportCode): \(airportName)")
    }
    // YYZ: Toronto Pearson
    // LHR: London Heathrow

所以这应该适用于您的示例。

var dict = ([
  "a number" : 1,
  "a boolean" : false,
  "a string" : "Hello"
  ])


for (k,v) in dict {
  if let x = v as? NSNumber {
    println("x = \(x)")
  }
}

您可以在 swift

中使用 is
var dict = ([
    "a number" : 1,
    "a boolean" : false,
    "a string" : "Hello"
])

for (key,value) in dict{
    if value is String{
        println(value)
    }
}

你也可以得到className

for (key,value) in dict{
   println(String.fromCString(object_getClassName(value)))

}

这将记录

Optional("__NSCFString")
Optional("__NSCFNumber")
Optional("__NSCFBoolean")

更新:

Swift 是一种类型安全语言,所以如果你有这样的字典

var dict = ([
        "a number" : 1,
        "a boolean" : false,
        ])

dict是[String : NSNumber]的类型,不需要检查

但是,如果你有这样的字典

 var dict = ([
        "a number" : 1,
        "a boolean" : false,
        "a string" : "Hello"
        ])

则dict是[String:NSObject]的类型,此时需要检查类型

更新,判断是Int还是Bool

最好将字典声明为 [String:Any] 那么

      var dict:[String:Any] = ([
        "a number" : 1,
        "a boolean" : false,
        ])

    for (key,value) in dict{
        if value is Bool{
            println(value)
       }
        if value is Int{
            println(value)
        }
    }

对于那些遇到警告问题的人,请确保按照@Leo 上述说明检查您的类型。如果你的值类型是 NSNumber,你会得到错误。如果它是 NSObject 类型,请使用@Leo 或@nPn 的答案。

这在我的项目中为我工作,它的值类型为 NSNumber:

for (key, value) in settings {

    if value == value as Bool {
        print(value)
    }
    if value == value as NSNumber {
        print(value)
    }
}

您还可以使用 dynamicType 找到 class,然后使用简单的 switch 语句来采取适当的操作

var dict = ([
  "a number" : 1,
  "a boolean" : false,
  "astring" : "Hello"
  ])

for (k,v) in dict {
  switch "\(v.dynamicType)" {
    case "__NSCFString":
      println("found String = \(v)")
    case "__NSCFBoolean":
      println("found Boolean = \(v as! Bool)")
    case "__NSCFNumber":
      println("found Number = \(v)")
    default:break
  }
}