Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 将guard与多种类型一起使用_Ios_Swift - Fatal编程技术网

Ios 将guard与多种类型一起使用

Ios 将guard与多种类型一起使用,ios,swift,Ios,Swift,我正在从服务器获取数据,其中一个值可以是NSDictionary或[NSDictionary]。我想知道是否可以使用新的Swiftguard来检查这两种类型。这就是我现在正在做的: guard let list = response["answer"] as? [NSDictionary] else { return nil } 但我想要这样的东西: guard let list = response["answer"] as? [NSDictionary] || let list =

我正在从服务器获取数据,其中一个值可以是
NSDictionary
[NSDictionary]
。我想知道是否可以使用新的Swift
guard
来检查这两种类型。这就是我现在正在做的:

guard let list = response["answer"] as? [NSDictionary] else {
    return nil
}
但我想要这样的东西:

guard let list = response["answer"] as? [NSDictionary] || let list = response["answer"] as? NSDictionary else {
    return nil
}

如果让,我不想使用
,因为我非常喜欢新语法。使用
guard
有什么方法可以实现这一点吗?

您可以使用关键字Is来了解类型(检查类型)

编辑:在操场上测试

var names: [String] = ["name 1" , "foo" , "Hotline Bling"   ,"vaudoo chills"]


func castingIs (sender : AnyObject) -> Bool {
    guard sender is String || sender is [String] else {
        return false
    }
    return true
}

castingIs(names) // true
castingIs(names[0]) // true
castingIs(4) // false

您可以使用关键字is来了解类型(检查类型)

编辑:在操场上测试

var names: [String] = ["name 1" , "foo" , "Hotline Bling"   ,"vaudoo chills"]


func castingIs (sender : AnyObject) -> Bool {
    guard sender is String || sender is [String] else {
        return false
    }
    return true
}

castingIs(names) // true
castingIs(names[0]) // true
castingIs(4) // false

我建议将可用性检查和类型检查分开

首先检查密钥是否存在

  guard let list : AnyObject = response["answer"] else {
    return nil
  }
然后检查类型

if list is NSDictionary {
  print("is dictionary")
} else if list is [NSDictionary] {
  print("is array of dictionary")
} else {
  fatalError("that should never happen")
}

我建议将可用性检查和类型检查分开

首先检查密钥是否存在

  guard let list : AnyObject = response["answer"] else {
    return nil
  }
然后检查类型

if list is NSDictionary {
  print("is dictionary")
} else if list is [NSDictionary] {
  print("is array of dictionary")
} else {
  fatalError("that should never happen")
}