smeshko
smeshko

Reputation: 1226

Using guard with multiple types

I'm getting data from a server and one of the values can either be an NSDictionary or [NSDictionary]. I was wondering if it was possible to use the new Swift guard to check for both types. This is what I am doing right now:

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

But I want something like this:

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

I don't want to use if-let, because I really like the new syntax. Is there any way to achieve this with guard ?

Upvotes: 1

Views: 325

Answers (2)

kholl
kholl

Reputation: 639

You can use the keyword is to know the type (https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TypeCasting.html checking type )

edit : test that in a playground

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

Upvotes: 2

vadian
vadian

Reputation: 285082

I'd recommend to separate the checks for availability and type.

First check if the key exists at all

  guard let list : AnyObject = response["answer"] else {
    return nil
  }

Then check the type

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

Upvotes: 2

Related Questions