You see a question mark (?) and an exclamation point (!) in the SWIFT program expression, what do they mean? These symbols are related to the optional type and the optional chain, and look at the optional chain below.
Optional chain:
Class Diagram:
Between them is a typical association relationship class diagram. These classes are generally entity classes, and entity classes are people, things, and objects in the system. The employee is associated with the department through the Dept property,department with the company through the comp attribute .
Here's the sample code:
[HTML]View PlainCopyprint?
- Class Employee {
- var No: Int = 0
- var name: String = "Tony"
- var job:string?
- var Salary: Double = 0
- var Dept: Department = Department ()
- }
- Class Department {
- var No: Int = Ten
- var name: String = "SALES"
- var comp: Company = Company ()
- }
- Class Company {
- var No: Int = $
- var name: String = "Eorient"
- }
- Let emp = Employee ()//employee instance
- Print (emp.dept.comp.name)//
Emp.dept.comp.name can refer to the company instance to form a chain of references, but this "chain" of any link "break" cannot refer to the final target (companyinstance).
Given an employee instance, there must be a department associated with it. But the reality is that a new employee may not have a department, this association can have a value, or it may not have a value, we need to use the optional type (Department?) to declare the Dept property.
Modify the code as follows:
[HTML]View PlainCopyprint?
- Class Employee {
- var No: Int = 0
- var name: String = "Tony"
- var job:string?
- var Salary: Double = 0
- var dept:department? = Department ()
- }
- Class Department {
- var No: Int = Ten
- var name: String = "SALES"
- var comp:company? = Company ()
- }
- Class Company {
- var No: Int = $
- var name: String = "Eorient"
- }
- Let emp = Employee ()
- Print (Emp.dept!.comp!.name)//Show unpacking
- Print (emp.dept?.comp?.name)//optional chain
A reference to the optional type, which can be displayed with an exclamation point (!), and the code is modified as follows:
Print (Emp.dept!.comp!.name)
However, there is a drawback to showing the unpacking, and if a link in the optional chain is nil, it will result in a code run-time error. We can use a more "gentle" way of quoting, using a question mark (?) insteadof the original exclamation point (!), as follows:
Print (Emp.dept?.comp?.name)
Swift Optional chain-ready