The model size is like Schrodinger’s cat


preface

As a Swifter beginner, it’s important to know what’s Optional

Let’s look at the official definition of Optional:

A type that represents either a wrapped value or nil, the absence of a value.

public enum Optional<Wrapped> : ExpressibleByNilLiteral {

    caseNone // The presence of a value, stored as' Wrapped '. /// The value in The Wrapped formcasesome(Wrapped) ... } Optional is an enumeration of two types, either null or with a value: var statusCode: Int? = 404 Null: var errorCode: Int? = nil = var errorCode: Int? (Default selectable value is nil)Copy the code

analogy

When we declare a selectable type in our code, use? To perform the

let number: Int? = 10 // number

So when we want to use the number value, let’s try printing it and get: Optional(10)

When we add number to a value of the same type, let a = number + 10, we get a compile-time error that means Optional(10) cannot be directly evaluated.

Force unpack!

At the back of the selectable by adding! In the form of untying by? The type of the wrapper number

let a = number! + 10 

# get a of type Int, not Int? , which means that a is definitely of type IntSo number, when we print it, number is still Optional(10)# means that forcing unpacking does not affect the type that was originally wrappedifletnumber: Int? = nil, force unpack number! Will collapseCopy the code

Let’s think about schrodinger’s cat

A cat in a box exists both dead and alive, and we don’t know the result until we open it

Schrodinger’s cat Selection can be let number: Int? = 10
The cat The type of the wrapper value Int?
The box Packaging value storage box Int? Storage place
? A rope for a cat ?
! The key to the box !

Here, we compare the dead or alive state to the presence or absence of a cat

? Like a lasso, when we put a lasso around a cat in a box, we don't know if there's a cat in the box

! Like the key to open a box, it depends on whether you can control it or not

Masturbators, they don’t cut nobodies, they don’t open doors

But in fact, when the box is not opened, there are at most two situations

1. Int? The cat is not 2. Int? The value of 10 cats are alive and kicking, ok stroking itCopy the code

We can’t just use the key to open the door

You’re all set for a cat stroke

Are you sad to find that there are no cats?

Can you imagine entering a bunch of pin numbers and checking your bank balance to find nothing

What would happen to you?

You're gonna crash. The system's gonna crash

But if we can open the door when we know there’s a cat,

Even though we took the cat out of the box, the box returned to its original state, and there were still two possibilities

Conclusion:

1. It is best not to force unpack 2 when we are not sure whether the selectable is worth it. Can be selected value, with! 3. Forced unpacking does not affect the type of the unpacked package. The unpacked type is still optional

Optionally bind the if let

Unpacking In addition to the rude behavior of forced unpacking, there are optional bindings

if let value = someOptional { 
    // doNext // if someOptional has a value, it will enterif// value is a value that someOptional forces to unpack. // Value is scoped only within {}if let /  ifVar} for example:let number = Int("777"// Int()"777") is also a type of Int initializer // returns a selectable // because if you pass a string"zzz"I can't convert it to an Int. It's indeterminateif let a = number {
    print("Conversion to Int successful",a) // Select number (777) as Optional(777)}else {
    print("Failed to convert Int"} * If there are multiple conditional optional values that need to hold together, e.gif let a = Int("1"),
   let b = Int("2") {
    print(a + b)} // omit oneif, spliced with commasCopy the code

If let is used with while

Var array = ["10"."10"."To 10"."a"]
var index = 0
var sum = 0
while let s1 = Int(array[index]),s1 > 0 {
    sum += s1
    index += 1
}
print(sum)
Copy the code

guard let

If the “if let” is the last step, then the “guard let” stands for an early exit

Guard is more comfortable to use than if

guard let value = someOptional else{// value if there is no value, it will enterelse// The scope of value is not limited to {} // It can be guardlet /  guard var 
    // must do return// Guard must return to exit current scope}print(value) // Here is the value of someOptional:let number = Int("777") 

guard let num1 = number else {   
    print("Conversion failed")
    return
}

print(num1 + 10) // Print 787Copy the code

Guard is compared to if

  1. Well organized
  2. Variables are more widely scoped
  3. Exit early, it’s more efficient

Null merge operator??

The system is defined like this:

func ?? <T>(optional: T? , defaultValue: @autoclosure () throws -> T?) rethrows -> T?Copy the code

Here’s an example:

Expression a?? B // It means: if a is not empty, return a, otherwise return b

  • Here are some caveats:

1. A must be selectable, the first parameter can be seen from the definition.. optional: T? , which proves that A must be selectable

2. The types of a and B must be identical except nil

Such as:let a: Int? = 10
let b: Int? = 20
letc = a ?? B // c = Optional(10Copy the code

3. B can be selectable or not

Such as:let a: Int? = 10
let b: Int = 20 
let c = a ?? b 

// c = 10
Copy the code

4. If A is not nil, return A, then the system does not involve B, b is redundant.

Note that the second argument to defaultValue: @AutoClosure () has an automatic closure
Automatic closures allow you to delay evaluation because the code snippet will not be executed until you call the closure
Copy the code

5. If A is not nil but B is not selectable, a will be unpacked automatically when a is returned

What does that mean? Such aslet a: Int? = 10
let b: Int = 20
letc = a ?? // c = a; // c = a; // c = a; Because the???? The following B is not selectable, so C is automatically unpackedCopy the code
  • conclusion

In fact, according to the official definition,…. T?) rethrows -> T?

?? Depending on the type of parameter b, what type is returned

Implicit solution package

Sometimes, in certain situations, an Optional can be guaranteed to always have a value (or should always have a value).

At this time each use are empty and reconciliation package, it appears a lot of

Add directly after the selectable initialization! Let it unpack automatically at compile time

Wouldn’t you think this timo is just another form of forced unpacking?

Forced unpacking is selectable

var aString: String? = "ttt"aString! // Force unpack"ttt"
Copy the code

Implicit unpacking is optional

var aString: String! = "ttt"// Implicit unpack * can still set nil, because aString is still selectable aString! // Force unpack"ttt"
aString  // Optional("ttt"AString = nil * If aString is assigned to bString, bString does not need to be unpackedlet bString: String = aString  
bString = "ttt"
Copy the code
So here's the question: 1. If I knew there was a cat in the box, would I try to catch it with a lasso? In other words do I still need to use selectable embellishment? 2. Why don't you just use the key to open the box? Why not just define it as String? 3. If I determine that it has always been valuable, in a sense, it will not lose the original intention of being selectable?Copy the code

My understanding, I do not know whether it is correct, please correct

We should all be aware of the controls in the XIB. When we drag out a button, we’ll see:

@IBOutlet weak var btn: UIButton! This BTN is implicit unpacking, right, which means that when you use this BTN, you automatically unpack it and get BTN

  • Why is this place implicitly unpacking? I think:

    • Each attribute is initialized with a value, either optional or implicitly unpacked
    • The dragged BTN will not be set until after the awakeFormNib initialization is complete
    • After initialization, it is most likely to be used, otherwise it would not drag the line
    • That is, the BTN will definitely exist, but only after initialization, unless you cut the cable
  • Then why not? Modified?

    • Most likely because of the use of? It’s a hassle to force unpack every time, so use the properties here!

Conclusion:

Implicit unpacking is not the most secure approach. Use it with caution

Reference :When You Should Use Implicitly Unwrapped Optionals

String interpolation

Sometimes we will give a warning when we print a string with selectable interpolation

var age: Int? = 10

The three fixes correspond to the solution in 3 below

print("zzz is \(age!) ") // Force unpackprint("zzz is \(String(describing: age))") // String initializationprint("zzz is \(age ?? 20)") // Null merge to default valuesCopy the code

There will be new additions in the future…

If you have any questions on your personal notes, please give me more advice

thanks for reading

.