Swift! And? The difference and use

  • 2020-05-27 07:19:38
  • OfStack

I believe that when you are learning and using Swift, you will surely be! And the & # 63; What the hell are these two symbols? Who knows when! , when to use ?

Just say 1! And the & # 63; The difference and how to use it!

The & # 63; And! What the hell is that?

The & # 63; And! They are actually syntax sugars for an optional type (Optional) operation in the Swift language. So what does the optional type do? In Swift, it is possible to declare a property without an initial value. In Swift, an optional type (Optional) is introduced to solve this problem. It is defined by adding 1 ? after the life of the type; Operator complete.

For example: var name: String?

Optional is actually an enum. There are two types of None and Some. In fact, the so-called nil is Optional.None, while the non-nil is Optional.Some, and then the original value of wrap is wrapped through Some(T), which is why the original value of Optional is unpacked (removed from enum).

This is the definition of enum Optional

enum Optional<T> : LogicValue, Reflectable { 
  case None 
  case Some(T) 
  init(_ some: T) 

  /// Allow use in a Boolean context. 
  func getLogicValue() -> Bool 

  /// Haskell's fmap, which was mis-named 
  func map<U>(f: (T) -> U) -> U? 
  func getMirror() -> Mirror 

In this case, for var name: String? How do you understand this grammar?

var name: String?

// the above declaration of Optional is "I declare a value of type Optional, which may contain a value of type String, or it may contain nothing", which means we are actually declaring type Optional instead of declaring type String.

The & # 63; And! use

When 1 is declared as Optional, there is a default value of nil if the assignment is not explicit. To determine whether a value of Optional has a value, if can be used to determine:

if name {
    // 有值再操作

How do I use the Optional value? It is also mentioned in the document that when using the Optional value, you need to add an ? in front of specific operations, such as calling methods, properties, subscript indexes, etc. If the value is nil, which is Optional.None, it will skip the following operation and not execute. If there is a value, which is Optional.Some, it may unpack (unwrap), and then perform the following operation on the unpacked value to ensure the safety of the operation.

/ / such as:

 let length = name?.characters.count 

PS: for the Optional value, do not directly operate, otherwise an error will be reported.

The & # 63; Usage scenarios:

1. Declare the Optional value variable
2. Used in the operation of Optional value to judge whether it can respond to the following operation
3. Use as & # 63; Downward transition (Downcast)

As mentioned above, the Optional value needs to be unpacked (unwrap) to get the original value, and then you can operate on it, so how do you unpack it?

There are two ways to unpack:

Optional binding (Optional Binding)

Optional binding (Optional Binding) is a simpler and more recommended way to unpack an optional type. Use an optional binding to check whether a variable of an optional type has a value or has no value. If there is a value, unpack it and pass the value to a constant or variable.

//  The example is the simplest 
var str: String? = "Hello"
let greeting = "World!"
if let name = str {
  let message = greeting + name

 Natural language interpretation meaning: is if str Have a value , Unpack it , And assign its value to name,  Then execute the following conditional statement ;  if str Is empty ,  Skip the conditional block directly. 

Hard to unpack

Hard unpacking is simply adding an exclamation point (!) to the optional type. To show that it must have a value.

var str1: String? = "Hello"
let greeting = "World!"
if (str1 != nil) {
  let message = greeting + str1!

 In the above example, we only know for ourselves str1 There must be some value ,  That's why I just unpacked it str1 The variable.   But all 1 Sometimes our feelings are wrong ,  The program may run with serious errors .  so Swift It is recommended to check if the optional type has a value first ,  And then we unpack it !

Error demonstration:

var str1:String?  // str1 A value may be a value passed in or retrieved from the server 
let msg = "Hi"
let txt = msg + str1! // runtime error

  The above code does not report errors at compile time . Because you're using hard unpacking ,  The compiler considers the optional type to have a value ,  So the compilation is ok .  When the code is running ,  Well-known errors will occur : `fatal error: Can't unwrap Optional.None`

PS: for! Operator, the variable value 1 is definitely not nil!

In fact, there is also an implicit unpacking (Implicitly Unwrapped Optionals). For example, the variable that will be initialized at viewDidLoad can be directly defined as var str: String! It means that every time you operate on a value of this type, you automatically add one before the operation! Do the unpacking, and then do the following operations. Of course, if the value is nil, crash will be incorrectly reported.

Take a simple chestnut:

//  in 1 a viewController Inside, from xib Dragging the 1 a UIImageView Controls,   You will find Xcode It will automatically give you the following form 

  @IBOutlet weak var headerBGImageView: UIImageView!

  The statement Implicitly Unwrapped Optionals Value, 1 General for properties in a class 

PS: if you implicitly parse an optional type without a value, crash is used. And unpacking in an optional type with no value is like 1.

! Usage scenarios

1. Force the Optional value to be unpacked (unwrap)
2. Declare implicitly unpacked variables, 1 normally used for properties in a class

The end of the

In fact! And the & # 63; Do not see it is only two symbols, because as long as there is one careless, not to pay attention to, you will find the project running, will inexplicably crash dropped, the key is that Debug mode is not very convenient to locate the wrong type. I will sort out 1 about the use of optional types by myself. 1 is to record and consolidate what I have learned, but I hope it will be helpful to you. There may be mistakes and inappropriacies in this paper. Please mention them and I will correct them in time.

Related articles: