??
Swift2.0 Study Notes ( Day )--optional chain
original articles, welcome reprint. Reprint Please specify: Dongsheng's blog
in theSwiftyou see a question mark in the program expression (?) and an exclamation point (!), 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. EmployeethroughDeptProperties andDepartmentAssociation,DepartmentthroughCompProperties and CompanyAssociation.
Here's the sample code:
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 = 10
var name: String = "SALES"
var comp: Company = Company ()
}
class Company {
var no: Int = 1000
var name: String = "EOrient"
}
let emp = Employee () // Employee instance
print (emp.dept.comp.name) //
Emp.dept.comp.namecan be referenced to Companyinstance to form a chain of references, but this "chain" of any link "break" cannot refer to the final target ( Companyinstance).
given aEmployeeinstance, there must be aDepartmentassociated with them. But the reality is that a new employee may not have a department, this association can have a value, or there may not be a value, we need to use the optional type (Department?) StatementDeptproperty.
Modify the code as follows:
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 = 10
var name: String = "SALES"
var comp: Company? // = Company ()
}
class Company {
var no: Int = 1000
var name: String = "EOrient"
}
let emp = Employee ()
print (emp.dept! .comp! .name) // Show unpacking
print (emp.dept? .comp? .name) // optional chain
where a reference to the optional type can be used, an exclamation mark ( ! ) to display the unpacking, the code is modified as follows:
Print (Emp.dept!.comp!.name)
However, there is a drawback to the display of unpacking, if a link in the optional chain isNil, it will cause code run-time errors. We can use a more "gentle" way of referencing, using question marks (?) to replace the original exclamation point (!), as shown here:
Print (Emp.dept?.comp?.name)
Welcome to follow Dongsheng Sina Weibo@tony_Dongsheng.
Learn about the latest technical articles, books, tutorials and information on the public platform of the smart Jie classroom
?
More ProductsIOS,Cocos, mobile Design course please pay attention to the official website of Chi Jie Classroom:http://www.zhijieketang.com
Smart-Jie Classroom Forum Website:http://51work6.com/forum.php
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Swift 2.0 Study Notes (Day 26)--optional chain