Alternative to if…case

This code for checking an enum with associated value is ugly…

           {
            if case .synonym(_, _) = tag
            {
              return false
            }
            
            return true
           }

Is there any way I can do something like…

           {
            return case .synonym(_, _) = tag ? false : true
           }
1 Like

Nope, not really. It’s an open topic for future evolution (see the core team feedback on the Result proposal), and you can create your own APIs to do this on a per-type basis, but those are pretty much your options.

OK. So it turns out it's quite simple boilerplate to add to the enum…

public enum Word
{
  case word
  indirect case synonym(Word, synonym: String)

  var isSynonym: Bool
  {
    if case .synonym(_, _) = self
    {
      return true
    }
    
    return false
  }
}

FYI, given an enum with associated values:

enum MyEnum {
  case a(Int)
  case b(String)
}

You can make a “helper” enum for its cases:

extension MyEnum {
  enum Case { case a, b }
  
  var `case`: Case {
    switch self {
      case .a: return .a
      case .b: return .b
    }
  }
}

Then you can do things like this:

func foo(_ x: MyEnum) {
  if x.case == .a {
    // ...
  }
}
4 Likes

would be cool to have a built-in protocol (say "CaseEnumerable") that provides this magic property out of the box.

Thanks Nevin. I rather like this. I have added it to my enum, which is a bit more complex than your example but it really makes coding a lot easier, especially when it involves having to do a switch on the enum case to see whether the subject is either one of several "ordinary" cases (which now all return the same Case) or one of the associated value ones, which now have their individual Cases.

And, for the sake of a few lines of code here, I now have several places where the code is so much easier to read.

1 Like

I believe it's impossible to do better than using the type name.

(EnumType.synonym ~= tag) == false

Make a !~= if you need it a lot.

Terms of Service

Privacy Policy

Cookie Policy