swift if case and optional binding

what is the difference between the three code blocks below?

  1. optional binding
let someInt: Int? = 42
if let x = someInt {
  print(x)
}
  1. enum case pattern
let someInt: Int? = 42
if case .some(let x) = someInt {
  print(x)
}
  1. optional case pattern
let someInt: Int? = 42
if case let x? = someInt {
  print(x)
}

Why a so simple functionality need 3 different syntax? It make the language too confusing!

And why the code below doesn't work?

let someInt: Int? = 42
var x: Int?
if case x? = someInt {
  print(x)
}

I just want to say, so damn confusing the language is.

1,2, and 3 are all equivalent to each other, with 1 and 3 being sugar for 2. I actually agree with you insofar as I think _? is visually cluttered, but if let and .some have good reason to be distinct syntaxes. Consider nesting your optionals

enum Authentication {
  case anonymous(password: String?)
  // ...
}

// ...

guard case let .anonymous(.some(password)) = x else {
  // log an error or something
}

And why doesn’t the code below work

Because Swift requires an introducer before a binding can occur. That is, the let and var keywords are required before you can use variables bound in patterns. To see why, consider this:

let password = “hunter2”
guard case .anonymous(.some(password)) = x else {
  // log an error or something
}

Now our condition only matches very insecure passwords instead of all the non-nil ones.

1 Like

two more ways:

switch someInt {
case let .some(x):
    print(x)
case .none:
    break
}

switch someInt {
case .some(let x):
    print(x)
case .none:
    break
}

Optionals have additional sugar because they appear very frequently. For example, in the type declaration, you've written Int? even though you could've written Optional<Int>. Many parts of the language are designed like that; things that are appear frequently have special syntax to provide better ergonomics.

I know what you mean. But too many abbreviations make the language too difficult to read. And the key point is that abbreviation dose not make the language simple. As the code snippets I written, how many "letters" does the abbreviation save? It just make confusion!
And as you said, "appear frequently", need a special syntax. "If ... else ..." statement, frequently enough? What about introduce a new syntax like "i ... e..." , simpler ? right? But it make the language hard to read. That what i mean. I think Swift need found a balance between simple and easy to read, not just simple.

Terms of Service

Privacy Policy

Cookie Policy