Swift's? And! The meaning of (turn)

Source: Internet
Author: User
Tags access properties class definition

In Swift, what do we often see and use? And! To talk about the two of them today.

Swift programming is nothing more than defining attributes or functions (methods), accessing attributes or calling functions, type conversions, and so on. And! In these processes, all have a skill, and, each time to consider the use of the time, they will appear together in our brains, with or without, if used, who to use?

1. Defining attributes

“? "Represents an optional type (optionals),"! "Indicates an implicitly selectable type (full name: Implicitly unwrapped optionals), which is still optional.

An optional type is the definition of a type that already exists (struct, Enum, Class) as an optional type, indicating that the value of the "new" type can be null nil. The writing format is followed by the original type with a "? such as

var nickname:string?

Defines an optional type string? Variable nickname, if we do not assign an initial value to nickname in a constructor (such as the Init function), then the system defaults to a nil as the initial value, in fact, when we define an optional type, the system immediately initializes the optional type variable or constant to nil. Before calling the Init method.

When accessing the optional Type property, if we determine that the property must have a value at this time, you can add "!" after the property name. "Tell the system," I'm sure this optional attribute has a value, force it out to use ", however, if the optional type attribute has a value of nil, then it will be crash. Oh. (If you access a property or call a function, you must use "!" Or "?", as described below), so visit, so, if it is nil, it will not cause crash. Therefore, a security check is usually done before the key point of the program uses an optional type to determine whether the actual value is nil. There are two methods of judging:


If nickname! = Nil {print ("\ (nickname)")}

If let Tempname = nickname {print ("\ (Tempname)")}

The second is called an optional binding, meaning that if the optional type nickname is not nil, it takes the value out of it, assigns it to tempname, and the type inference tempname to NSString, because determining the amount after the equal sign is not nil is the assignment, so Tempname is not an optional type, the assignment succeeds, at this time equivalent if True {... }, if the value of nickname at this time is nil, please make your own brain fill.

“ ! ", an implicitly selectable type, is an optional type, and the writing position is the same as"? ", the difference is, with"! " Optional type of declaration, you can access the property without writing "!" To take out the real value of the property, and this tells the system that I know that this property will always have a value in its survival process. In fact, accessing your own optional type attribute in the controller is required! "To fetch the value, this action is officially called forced unpacking (forced unwrapping). The above said value, in order to facilitate understanding. Can you be more professional? Under unified use unpacking.

var nickname:string!

Note: If the implicit optional type attribute may be nil in the life cycle, do not define it as "! "Type of A." It's going to crash.

2, define the function? (Are you kidding me?) )

“? "and"! "is a function that can be used to define functions. Classes, structs, enumerations are required constructors, then, sometimes according to some business requirements, we will determine that this instance of the construction process failed, so, there is a failure of the constructor. Examples of official documents are as follows:

Class Product {

Let name:string!

Init? (name:string) {

Self.name = Name

If Name.isempty {return nil}



So, see init? and init! , do not panic, is to instantiate the type may be empty, may construct (create) failure, the failure will return nil, although Swift does not want to be in OC, the need to return self in the Init method. In the example above, if the construction succeeds, for example:

Let newproduct = Product ("Chocolate")

Based on the product class definition, the construction instance succeeds, and the newproduct type is inferred as product?. (unless you are hard to add an optional type after the variable or constant of the receiving instance, do not, really ...) )

As a base friend, how can not "!" The thing! As a matter of fact, only if the construction succeeds, the type of the returned instance is inferred as product! (implicit optional)

It is important to emphasize that if the currently instantiated class is a class Koziko class, for example, we have customized a UIButton subclass Basebutton, and defined Pybutton:basebutton, when instantiating Pybutton, if it fails, Then in the instantiation process of the successor chain no matter what step to take, stop immediately.

3. Accessing properties and calling functions

These two chat together, when we access properties or call a function, because Swift allows a variety of hyphen syntax to be used together, so sometimes there will be a large number of point syntax successive calls, property access and function calls intersect each other, in this process, if you encounter an optional type what to do? To write a bunch of "! "Unpacking?" The answer is in the negative.

Swift provides a mechanism called "Nullable chain Call", in a series of point syntax calls and accesses, simply add a "to the caller"? , indicating that if any step fails during the execution of this sequence of point syntax, the entire point syntax chain stops and returns nil as a whole, without error, without crash. Well, here's the problem, use "! "Can't You?" OK! However, if the step return value is nil in the point syntax chain, it will cause crash. Since we cannot always guarantee that the return value of a piece of code is not nil, or the property is nil, or fails, then use "? "is excellent.

On the code:

Class Person {

var telstring:string?


Let xiaoming = person ()

Print ("\ (xiaoming.telstring!. Intvalue)//crash, because telstring is nil, forcing the unpacking is crash

Print ("\ (xiaoming.telstring?. intvalue)//output: Nil

4. Type conversion

We all know that there are many states in OC, in some cases, we will assign the subclass instance to the parent pointer, and then back to the subclass when it is used. In Swift, in this case, use as? and as! To do, if you want to determine the type of an instance with IS. A as? B means that if instance A is a type B or a subclass of type B, it converts the type of a to type B, returns the converted instance (which is optional type B?), and if not, returns nil, and the program continues to run. If you use as! , stating that we are sure that a is a subclass of type B or B, then the cast, if not, will be crash. Like what

Class Teacher:person {

var teachingid:string

Init (teachingid:string) {

Self.teachingid = Teachingid

Super.init ()



Class Student:person {

var studentid:string

Init (studentid:string) {

Self.studentid = StudentID

Super.init ()



Let teacher = Teacher ("12345")

Let student = student ("987")

Let classcontact = [Teacher,student]

Note: The type of classcontact at this time is: [Person]

For who in Classcontact {

If let teacher = person as? Teacher {//code}

else if let student = person as? Student {//code}


As! in the case of self-brain repair. Simply mentioned is, it is equivalent to the Iskindofclass in OC: Method.

In addition, there are two question marks linked together, in fact, it is very simple, first look at the code:

Let name = "Panyu"

Let nickname = Name?? "Hehe"//If Name is nil (of course this example will not be nil), then the expression return value is "??" After the value, if name has a value, then the expression returns the value of the name itself

One word?? An expression is a simple version of the three-mesh operator.

Swift's? And! The meaning of (turn)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.