I believe that when you learn and use Swift, you will certainly be! And? Crazy, what the hell are these two symbols? Ghosts know when to use!, when to use?
Let's talk about it! And? Difference and how to use it!
? And! What the hell is that?
? And! In fact, the syntactic sugars in the swift language for an optional type (Optional) operation. What is the optional type? Swift can declare a property without an initial value, and Swift introduces an optional type (Optional) to solve the problem. Is it defined by the life after the type of the Gaga one? operator to complete.
For example: Var name:string?
Optional is actually an enum, which has two types of none and some. In fact, the so-called nil is optional.none, nil is optional.some, and then through the Some (T) packaging (Wrap) The original value, which is why the use of optional when you want to split (from the enum to take out the original value) reason.
This is the definition of the enum optional.
Enum optional<t>: Logicvalue, reflectable {case
None case
Some (T)
init () init (
_ Some:t)
// /Allow a Boolean context.
Func getlogicvalue ()-> Bool
///Haskell ' s Fmap, which was mis-named
func-map<u> (f: (T)-> u)-> u?
func getmirror ()-> Mirror
}
In that case, what about Var name:string? How to understand this grammar?
var name:string?
The optional statement above is "I declare a optional type value that may contain a string value or nothing," which means that we actually declare the optional type rather than declaring a string type ( This actually understand to be very egg ache ...)
? And! Use
Once declared as optional, there will be a default value nil if no explicit assignment is made. To determine whether a optional value has a value, you can use if to determine:
if name {
// 有值再操作
}
How to use optional value? It is also mentioned in the document that you need to add one before using the optional value, such as calling methods, attributes, subscript indexes, and so on, if the value is nil, That is Optional.none, will skip the subsequent operation does not execute, if there is a value, is optional.some, may be unpacking (unwrap), and then after the value of the unpacking after the operation, to ensure the security of this operation.
For example:
let length = name?.characters.count
PS: For the Optional value, can not directly operate, otherwise it will be an error.
? The use of the scene:
1. Declaring optional value variables
2. Used in the operation of the optional value to determine whether the following actions can be answered
3. Use as? Downward Transition (downcast)
It is mentioned above that the optional value needs unpacking (unwrap) to get the original value before it can be manipulated, then how to unpacking it?
There are two ways to split a package:
Optional bindings (Optional Binding)
An optional binding (Optional Binding) is a simpler and more recommended way to unpack an optional type. Use an optional binding to check whether a variable of an optional type has a value or no value. If there is a value, unpack it and pass the value to a constant or variable.
The most straightforward example is the
var str:string = "Hello" let
greeting = "world!"
If let name = str {let message
= greeting + Name
print (message)
}
/**
Natural language interpretation meaning: If Str has a value, unpack it, and assigns its value to name, and executes the following conditional statement; If Str is empty, skip the conditional statement block directly.
*/
Hard Solution Package
A hard unpack is an exclamation point (!) directly behind an optional type to indicate that it must have a value.
var str1:string? = "Hello" let
greeting = "world!"
if (str1!= nil) {Let message
= greeting + str1!
Print (message)
}
/** The
above example, we just know that str1 definitely have a value, so we directly solve the STR1 variable. But if sometimes our feelings are wrong, the program may run into serious errors. So Swift is recommended to first check whether the optional type has a value, and then unpack!
*/
Error Demonstration:
var str1:string? The STR1 value may be a passed value or a value obtained from the server let
msg = "Hi" let
txt = msg + str1!//Runtime error
/**
The code above is not an error at compile time. Because the hard solution is used Package, the compiler considers the optional type to be a value, so the compilation is passed. When the code runs, a well-known error will appear: ' Fatal Error:can ' t unwrap optional.none '
*
PS: For! operator, the value of the variable here must be nil!
In fact, there is also an implicit unpacking (implicitly unwrapped optionals), such as for variables that are initialized in Viewdidload, that can be defined directly as Var str:string! is equal to say that every time you operate on this type of value, you will automatically make up one before the operation! Do the unpacking, and then after the operation, of course, if the value is nil, the error crash out.
A very shallow chestnut:
In a viewcontroller, drag a Uiimageview control from the Xib, and you'll find that Xcode automatically turns you into the following form
@IBOutlet weak var Headerbgimageview: uiimageview!
/**
declares implicitly unwrapped optionals value, generally used for properties in the class.
PS: If you are implicitly parsing an optional type without a value, it will crash. It's the same as unpacking in an optional type with no value.
! The use of the scene
1. Force the optional value to be split (unwrap)
2. Declare an implicit unpacking variable, typically used in a property in a class
End
In fact! And? The problem is very pit, do not look at it is only two symbols, because as long as there is a careless, do not notice, you will find that the project to run up, will be inexplicable crash off, the key is the debug mode is not very easy to locate the wrong type. Organize yourself about the optional type of related use, one is to record and consolidate the learning, but hope will be helpful to everyone. This article may have the mistake and the improper place, also hoped that proposes, I will promptly correct.