Home > Back-end >  How to check enum type in Swift in a more concise way?
How to check enum type in Swift in a more concise way?

Time:09-19

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)
}

CodePudding user response:

Most succinct now:

if case DataToValidate.object = instance {
  return true
}

return false

Might become better:

instance is case DataToValidate.object

CodePudding user response:

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
}

CodePudding user response:

If the case is about checking one type only, you could try:

return i == .object
  • Related