class Car { var price = 0 }
class Dog { var weight = 0 }
class Person {
var name: String = ""
var dog: Dog = Dog()
var car: Car? = Car()
func age() -> Int { 18 }
func eat() { print("Person eat") }
subscript(index: Int) -> Int { index }
}
Copy the code
var person: Person? = Person() var age1 = person! . The age () / / Int! Forced unpacking may crash var age2 = person? .age() // Int? ? Optional if person is nil, it doesn't execute, okay? Age () var name = person? .name // String? var index = person?[6] // Int?Copy the code
- If optional is nil, method, subscript, property calls fail and result is nil
- If the optional is not nil, the method, subscript, and property are called successfully, and the result is wrapped as optional
- If the result is already optional, it will not be repackaged