Example of the use of commas in Swift conditional judgment

  • 2020-05-30 21:10:51
  • OfStack

preface

It is well known that in the Swift language, Bool values are used for conditional judgment and can be used & & And the operation of ||, so as to realize the common judgment of multiple expressions.

However, because of the optional binding in Swift, or expanding the option with let, there are some places where conditional judgment cannot be used & & So let's do that. For example, we need to execute the code when the variable hasValue does have a value and the number of parameters paramCount is greater than 0. In general, we can write:


 if hasValue != nil && paramCount > 0 {
 ...
 }

However, if we want to use the hasValue value in the subsequent code, we can't just tell if hasValue is nil, but should use the optional binding to read the value, which is the following code:


 if let hasValue = hasValue {
 if paramCount > 0 {
  ...
 }
 }

Due to the let hasValue = hasValue An Bool value is not returned, resulting in two conditions that cannot be used & & To make a judgment, we use what is known as a comma, which means that we can write:


 if let hasValue = hasValue, paramCount > 0 {
 ...
 }

This way we can meet our needs. The code will force the above code to have one less layer of judgment, so it will look more friendly. This is especially handy when you need to optionally bind multiple variables. Such as:


 if let a = a, let b = b, let c = c, let d = d, e < 0, f > 0 {
 ...
 }

If you don't use it, split it up, but use it as a one-by-one judgment, you'll end up in a multi-judgment pit, making your code bloated.

In general, the role of the comma in conditional judgment is similar to that of & & , but it can be used to connect optional bindings as well as Bool values.

conclusion


Related articles: