1, Optional can be set to nil. Other types cannot be set to nil. A???? B The type of the return value

// MARK: Optional can be set to nil. Other types cannot be set to nil. A???? Func testOptional() {var name: String? = "jack" name = nil // Force unpack optional force unpack with value nil, resulting in runtime error (crash) let age: Int? = 10 print(age!) if name == nil { print("name is nil") } else { print(name!) } let num = Int("123") // num = optional if num! = nil {print(" string to integer success: \(num!)) ")} else {print(" conversion failed ")} // The scope of automatic unpacking is limited to braces if let number = Int("123") Print (" string to integer success: \(number)")} // Optional If let first = Int("4"), let second = Int("42"){print("success")} // a ?? // If a is not nil, a is returned, and if b is not optional, a is unpacked. // If a is nil, b is optional, // The storage type of b and A must be the same. Let a: Int? = 1 let b: Int? = 2 let c = a ?? b print("c=\(String(describing: c))") let e: Int? = 3 let f: Int = 4 let g = e ?? f print("g=\(g)") }Copy the code
// MARK: optional implicit unpack num1 is optional! Unpack for implicit, cannot be used when nil! Func hiddenOptional() {let num1: Int! = 10 let num2: Int = num1 print(num1 ?? 0,num2) }Copy the code
  • Optional with switch
var age: Int? = 10 switch age { // ? Case let v? : print(v) case nil: print("2")} equivalent to: if let v = age {print(v)} else {print("2")}Copy the code