Matching enum case and only some properties

Is there a way to match on a enum case and only get one or two of its properties?

enum FolderChildInfo {
    case folder(name: String, id: UUID)
    case file(name: String, id: UUID, isEncrypted: Bool, size: UInt64)
    ...
}
...
// This doesn't compile
switch info {
    case .file(id: let id):
    // or...
    case let f = .file: 
        ... f.id ...
// All these are equivalent
case let .file(_, id: id, _, _): ...
case .file(_, id: let id, _, _): ...
case .file(_, let id, _, _): ...
case let .file(name: _, id: id, isEncrypted: _, _): ...

You can pretty much max-n-match where to put let/var, whether to use labels, etc., but you need a correct number of associated values.

Personally, I tent not to use labels (isEncrypted, etc.) unless it's ambiguous otherwise.

1 Like

Okay, thank you. I'm not sure whether to use an enum or declare a few struct types and match with the as pattern. I guess it's a matter of taste.

switch x {
  case let f as FileInfo:
    ... f.name ...

Note that case as is a runtime check, which may not be what you'd expect.

My rule of thumb is that:

  • If it has a fixed number of possible type, and rarely changes, use enum
  • If there are a lot of the possible type, or you expect the downstream users to their own types, use protocol.