SoFunction
Updated on 2025-04-04

Detailed explanation of swift implicit optional instance

1. Basic use of implicit optional

var errorMessage: String? = nil
errorMessage = "Not Found"
"The message is " + errorMessage!

Definition of implicit optional

var errorMessage: String! = nil
errorMessage = "Not Found"
"The message is " + errorMessage

Implicit optional models do not require unpacking, so implicit optional models are prone to errors

The above program will report an error when errorMessage is nil

2. The practical application of implicit optional

// It is mainly used in the initialization of class member variablesclass City{

  let cityName: String
  unowned var country: Country
  init( cityName: String , country: Country){
     = cityName
     = country
  }
}

class Country{

  let countryName: String
  var capitalCity: City!

  init( countryName: String , capitalCity: String ){

     = countryName

     = City(cityName: capitalCity, country: self)
  }

  func showInfo(){
    print("This is \(countryName).")
    print("The capital is \().")
  }
}

let china = Country(countryName: "China", capitalCity: "Beijing")
()

Thank you for reading, I hope it can help you. Thank you for your support for this site!