Many students ask optional? And! Difference, to figure this out, let's first look at the optional syntax in Swift
The swift language uses VAR to define variables, but unlike other languages, Swift does not automatically assign an initial value to a variable, which means that the variable does not have a default value, so it must be initialized before it is required to use the variable. If you do not initialize before using the variable, you will get an error:
var stringvalue:string//error:variable ' stringvalue ' used before being initialized//let hashValue = Stringvalue.hashva lue//Let HashValue = Stringvalue.hashvalue
the above is the normal value, the next optional value to play. remind that optional is actually aenum, there areNoneand theSometwo different types. In fact, the so-called nil isOptional.None, non-nil isOptional.Some, and then you passSome(T)Wrapping (Wrap) raw value, which is why you want to unpack (extract the original value from enum) when using optional
Declaring as optional only needs to be followed by a type ? . Such as:
var strvalue:string? ? The syntactic sugar var strvalue:optional<string> equivalent to the following notation
The above statement of optional, meaning "I declare a string value of optional", but "I declare a optional type value, which may contain a string value, or it may contain nothing", That is to say, we are actually declaring the optional type, rather than declaring a string type, which we need to keep in mind.
Once declared as optional, there is a default value of nil if no explicit assignment is made. To determine whether a optional value has a value, you can use the IF to determine:
If strvalue {//do sth with strvalue}
example:
var opt: int? opt = 10if opt != nil { if opt != nil{ print ("true") print ("true")}else{ else{ print ("false") print ("false")} }
Usage var instr:string = "xxx" var intopt:int? = Int (INSTR) if (intopt! = nil) {var intvalue:int = intopt!}
Try it! To access a optional value that does not exist will trigger a run-time error. When we use! To force the unpacking (Force-unwrap),
Make sure that this optional value must contain a non-nil value.
Implicit unpacking optional values (implicitly unwrapped optionals)
Sometimes, we can be sure that once a variable or constant has been created and initialized, it always has a value, so you can get the value by using an implicit unpacking method.
When declaring a variable, it is not used? To declare an optional value, use it instead! To declare.
Such as:
Let possiblestring:string? = "An optional string." This is mandatory unpacking println (possiblestring!) Let assumedstring:string! = "An implicitly unwrapped optional string." No need to add! To dismantle the package println (assumedstring)
This article is from the "focus on the latest technology" blog, be sure to keep this source http://2445109.blog.51cto.com/2435109/1732805
Optional usage and frequently asked questions in Swift