When using optional types and optional chains, the question mark (?) and exclamation point (!) are used more than once,but they have different meanings, let me explain in detail below.
1. Question mark (?) in the optional type
Declares that this type is an optional type, to use an exclamation point (!) when accessing a variable or constant of this type, and the following code shows the split package:
- Let result1:double? = Divide (100, 200)
- Print (result1!)
2. Exclamation mark (!) in an optional type
Declaring this type is optional, but you can access this type of variable or constant without using an exclamation point (!), and the following code is implicitly unpacking:
- Let result3:double! = Divide (100, 200)
- Print (RESULT3)
3. Exclamation point in the optional chain (!)
Multiple instances have an association, and a reference chain is formed when a member of another instance's methods, properties, and subscripts are referenced from one instance, and since some links in this "chain" may have values or no values, they need to be accessed in the following way:
- Emp.dept!.comp!.name
4. Question mark (?) in the optional chain
When using an exclamation mark (!) in an optional chain,once the "chain" has no value, the program will have an exception, we'll change the exclamation point (!) to a question mark (?), and the code looks like this:
- Emp.dept?.comp?.name
This returns nil when there are no values for certain links , and the program does not have an exception.
Swift summary using question mark (?) and exclamation point (!)-Alternate