How to check enum type in Swift in a more concise way?

Viewed 45

This is how I check enum type. Is it a way not do it with switch but shorter?

if let i = instance as? DataToValidate {
    switch i {
       case .object:
        return true
       default:
        return false
    }
} else {
    return false
}

And my type:

public enum DataToValidate {
    case object(JSONObject)
    case array(JSONArray)
    case string(String)
}
2 Answers

Most succinct now:

if case DataToValidate.object = instance {
  return true
}

return false

Might become better:

instance is case DataToValidate.object

The if and guard statements allow you to use pattern matching.

if case DataToValidate.object = instance {
    return true
} else {
    return false
}

If you want to use the associated value, you can bind it:

if case DataToValidate.object(let object) = instance {
    return object
} else {
    return nil
}
Related