So in Swift we’re going to have Optional, when you start writing code it’s going to be after the variable, right? ,! And???? And so the symbols get confused.

First, for the following code:

var num: Int? Num = 10 if num is Optional<Int> {print(" print ")} else {print(" print ")}Copy the code

Warning: ‘is’ test is always true. Num is not an Int, but an Optional.

1. The Optional type

Optional type declarations, as follows:

var num : Int? // let num2 : Int? // Let variables can only be initialized onceCopy the code

We declare a variable whose value can be an Int or nil. That is, we are actually declaring a variable of type Optional, not an Int.

It is precisely because num is an optional type that it can be assigned nil. Var num: Int = nil, which cannot be successfully assigned, because there is no such thing as nil in Int! In OC objects can be assigned nil, but in Swift only Optional types can be assigned nil!

2. About unpacking

Unpack symbol is!

If it is certain that a value of an optional type must exist, then we use! Unpack to get its value, or use an Optional Binding.

let possiablestring: String? = "An possiable string" print(possiablestring!) Let strValues = possiableString! .hashValueCopy the code

You can also think of implicit unpacking optional types as optional types that are automatically unpacked every time they are used. Implicit unpacking does not end with a variable/constant every time it is used! Instead, add it directly to the definition. .

let assumString: String! = "an optional string"
print(assumString, assumString.hashValue)
Copy the code

! The use scenario of

  1. Force unpacking of optional class variables;
  2. When declaring an implicitly unpacked optional type variable, it is typically used for a property in a class.

3. Basic idea of unpacking

Use an if let or guard let instead of forcing unpacking. For the following methods:

func getHeight(_ height: Float?) -> Float? { if height ! = nil { return height! / 100 } return nil }Copy the code

Used in the above code! Unpack height, and then participate in the operation, unpack height each time it is used. If unpacking fails during forced unpacking, it will cause a crash. The safe unpacking behavior should be handled by an if let or guard let operation called optional binding:

// if let 
func getHeight(_ height: Float?) -> Float? {
    if let unwrapedHeight = height {
    return unwrapedHeight / 100
  }
  return nil
}

//// guard let
//func getHeight(_ height: Float?) -> Float? {
//  guard let unwrapedHeight = height else {
//    return nil
//  }
//  return unwrapedHeight / 100
//}
Copy the code

Note: For the if let, braces are the normal case that meets the condition, while the outer case is not the normal case; For guard lets, the brace in Guard let else is the exception case, while the outer returns the normal case.

Having several front-guard lets for judgment can sometimes make code more readable.

4. Optional chain unpacking

For these two classes:

class Person {
  var phone: Phone?
}

class Phone {
  var number: String?
}
Copy the code

There is no need to make a judgment layer by layer when unpacking, because if any of the optional chains is nil, then nil is returned, as follows:

let dora = Person() guard let number = dora.phone? .number else { return }Copy the code

5. _Nonnull, relationship between nonNULL and optional types

For the concatenated string method, OC looks like this:

- (NSString *)stringByAppendingString:(NSString *)aString;
Copy the code

In Swift it looks like this:

public mutating func append(_ other: String)
Copy the code

Just from the API, the OC entry is dangerous because it is of type NSString *, so nil can also be passed in, which will crash, and should be written as:

- (NSString *)stringByAppendingString:(NSString * _Nonnull)aString; //// or //- (NSString *)stringByAppendingString:(nonnull NSString *)aString;Copy the code

This will remind the programmer that the input parameter cannot be empty. Swift doesn’t do that, other is a String, not a String, okay? , indicating that the input parameter is a non-optional type.

Reference article:

www.mamicode.com/info-detail… www.jianshu.com/p/4bfbb0ba4…