如何评估 Swift 的“ if let”?

我在 Swift 网站上看到过这段代码,在这里看到过各种各样的帖子,我正试图掌握这些基础知识。如何计算这条线?

if let name = optionalName {

我很困惑,因为它不是 name = = 可选的 name,而是赋值,那么如何报告 true 和 为什么它不是真的,当你用零代替约翰苹果种子,因为它仍然是相等的?

var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello, \(name)"
}
109832 次浏览

Essentially the line is saying, "if you can let the new variable name equal the non-optional version of optionalName, do the following with it". As Martin pointed out, this is called Optional Binding.

The sole purpose of it is to test if an optional variable contains an actual value and bind the non-optional form to a temporary variable. This is the safe way to "unwrap" an optional or in other words, access the value contained in the optional. It is in no way testing for equality of any kind. It is only testing for the existence of a value within an optional.

The if syntax accept 2 different conditions. The second, an optional binding, is not a boolean. This is confusing, as you can write:

if let name = optionalName {

but not

if (let name = optionalName) {

Apple documentation (Swift reference):

The value of the condition must be of type Bool or a type bridged to Bool. The condition can also be an optional binding declaration, as discussed in Optional Binding.

Whenever you are working with weak references, optional types it would be better to use if let to safe guard your code and avoid crashes Here is the examples

var middleName :String? = "some thing"
if let isExistsMiddleName = middleName {
// do some thing here
} else {
// no middle name
}

if only takes boolean expressions, other than that it would throw an error, so this code snippet saying

if let name = optionalName {


}else{


}

if optionalName is nil then the condition is false and else statement will execute. However if optionalName has some value then the optional value is unwrapped/assigned into the constant variable ie name.

An optional is either set or not-set (not nil or nil)...leaving us with an important decision. "How should we write our code so that it can work correctly for 2 both states?". The way we unwrap the optional is what decides that for us.

There are several approaches that you can use to counter a not-set optional.

  • Crash!
  • Default the value to something — if it was not-set.
  • Gracefully fail ie do nothing, but also if the value was set, then assign it.
  • Gracefully fail ie do nothing, however if the value was set...do something (it's just more than a single assignment).

Below are the 4 approaches


Using forced unwrapping will crash if you don't have a value. You would want to do this if having that value is of vital importance e.g. the title of a movie (every movie MUST have a name) . ! is used for forced unwrapping.

movieTitle = movie.title!

Using nil coalescing is another way that will give you more control, meaning it won't crash if the value isn't set, nor it would 'not set it nothing' if it's not set...it would do what you tell it to do e.g. it would default/set the name of movie to untitled_movie if there was no name set. ?? is used for nil coalescing.

var movieTitle = movie.title ?? "untitled_Movie"

Using optional Chaining will do nothing if you don't have a value, and will set the value if you have a value. You do this for something that having its value set is not of vital importance e.g. for the name of your actor's agent.? is used for optional chaining.

let agent = movie.leadActor?.agent //would not crash if you don't have a lead actor (optional chaining)
let agent = movie.leadActor!.agent //would crash if you don't have a lead Actor (forced wrapping)

Using if-let ( or guard which are two different types of optional binding) will give you more control, it won't crash if the value isn't set. If the value is set, then you can do something. If it's not set then you can add an else statement.

if let supportingActor = movie.supportingActor{
print(" The supporting actor is \(supportingActor)}

This is the most commonly used way of unwrapping, as forced unwrapping is somewhat discouraged. For more discussion on why it is discouraged see here. For a good comparison between guard and if-let see guard vs. if-let


Side note:

Optional binding and optional chaining are commonly used together:

if let agent = movie.leadActor?.agent {
ContactInfo = agent.phoneNumber
} // if-let is the optional *binding* part, the movie dot leadActor dot is the optional *chaining*