Why swift do not add the `not` keyword?

In most situations to determine whether a variable is not a Type we need to add !() around the expression, e.g.: !(variable is HomeViewController). Why the Swift language does not add the not keyword to simplify it: variable is not HomeViewController?

Swift isn't COBOL or Apple Script. It prefers to keep keywords to a minimum.

2 Likes

I would welcome a solution for the is test myself as well, though I don't think that adding a new keyword is right either.

An easier solution would be something like

value !is MyType

4 Likes

You can always use something like…

  if let controller = variable as? HomeViewController
  {
    …
  }

… or…

  guard let controller = variable as? HomeViewController else
  {
    return
  }
  
  …

This is a "shortcut" instead of constructs like…

  if !(variable is HomeViewController)
  {
    (variable as SomethingElse).…
  }
1 Like

Sounds good~

There are many usecases where you don't need the variable casted to something else, you just need to know whether it's not a specific type. This is IMHO similar to #available which until recently needed to be solved like this:

if #available(macOS 11) { /* nothing */ } else {
    // Here goes the special pre-macOS 11 code
}

(Yes, now you can use #unavailable, but it's been years before that was added.)

Just like that, you can be using

if variable is Something { } else {
    // Here goes code when it's NOT Something
}

But the legibility of the code is indeed poor.