Original articles, welcome reprint. Reprint Please specify: Dongsheng's Blog
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:
classEmployee {varNo:int =0 varName:string ="Tony" varJob:string?varSalary:double =0 varDept:department =Department ()}classDepartment {varNo:int =Ten varName:string ="SALES" varComp:company =Company ()}classCompany {varNo:int = + varName:string ="eorient"} let EMP= Employee ()//Employee Instanceprint (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 (company instance).
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:
classEmployee {varNo:int =0 varName:string ="Tony" varJob:string?varSalary:double =0 varDept:department?//= Department ()} classDepartment {varNo:int =Ten varName:string ="SALES" varComp:company?//= Company ()}classCompany {varNo:int = + varName:string ="eorient"}let EMP=Employee () print (Emp.dept!.comp!.name)//Show Split PackagePrint (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 (?) instead of the original exclamation point (!), as follows:
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 Products iOS, Cocos, mobile design courses please pay attention to the official website of Chi Jie Classroom: http://www.zhijieketang.com
Luxgen Classroom Forum Website: http://51work6.com/forum.php
Swift 2.0 Study Notes (Day 26)--optional chain