Swift - Case 语句和 MetaType 检查?

标签 swift

给定一个字典,我需要检查它的值是字典、数组还是其他。 我收到以下错误:

Downcast pattern value of type Dictionary cannot be used

// Type of dictionary to enumerate through
public typealias SourceDictionary = [String: AnyObject]
var dictionary: SourceDictionary


for (key, value) in dictionary {
   switch (value) {
      case value as SourceDictionary :
         print("Dictionary")

      case value as Array :
         print("Array")

      default :
         print("Other")
   }
}

也试过

case let someValue as SourceDictionary

最佳答案

您可以使用 switchif 语句进行检查,只是您的语法不太正确。

切换:

for (key, value) in dictionary {
    switch value {
    case let v as Dictionary<String, AnyObject>:
        println("Dictionary in \(key)")
    default:
        println("other")
    }
}

如果:

for (key, value) in dictionary {
    if let v = value as? Dictionary<String, AnyObject> {
        println("Dictionary in \(key)")
    }
}

关于Swift - Case 语句和 MetaType 检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25579081/

相关文章:

swift - 从 RayCasting 获取平面大小

ios - 如何在iOS设备上快速合成/刺激触摸事件?

swift - Swift 中的隐式惰性静态成员

swift - UIView 阴影在 iphone 5s 中不显示

swift - 尽管在 Swift 3 上转换为 AnyObject,类型 "Any"没有下标成员?

swift - 平滑 NSWindow 调整大小重新 : contentSize of WKWebView

swift - 用于 UiWebView 的 UIMarkupTextPrintFormatter

ios - SKSpriteNode 纹理黑框

swift - 节点不旋转?

swift - 将 SF Symbols 添加到 UIAlert 的标题中