Why is there optional
There is no optional type in OC. All object variables in OC can be nil becausenil
Is a typeless pointer. Dictionaries, arrays, and collections cannot be placed in OCnil
,nil
It can only be used on OC objects. Variables are not convenient to some extent, but they are different in swift. In swiftnil
And in OCnil
There is a big difference. In OCnil
Is a pointer to a nonexistent object, but in swift,nil
It is not a pointer, but a special type with missing value. Any type option can be set tonil
. Therefore, in swift, the optional value can benil
, to express the missing value of variables, which increases certain convenience.
In swift, we add?
To represent an option, for example:
var name: String? = nil
Implementation of optional
Optional is actually an enumeration type. We can see from the code in the standard library
@frozen public enum Optional<Wrapped> : ExpressibleByNilLiteral {
/// The absence of a value.
///
/// In code, the absence of a value is typically written using the `nil`
/// literal rather than the explicit `.none` enumeration case.
case none
/// The presence of a value, stored as `Wrapped`.
case some(Wrapped)
/// Creates an instance that stores the given value.
public init(_ some: Wrapped)
This enumeration has two values. The code optional has two meanings
- none
Represents that the variable has no value, that isnil
- some
Represents that the variable has a value, and the value issome
,some
Packed actual value
If you get the actual value, or if you look at the code in the standard library,
/// The wrapped value of this instance, unwrapped without checking whether
/// the instance is `nil`.
///
/// The `unsafelyUnwrapped` property provides the same value as the forced
/// unwrap operator (postfix `!`). However, in optimized builds (`-O`), no
/// check is performed to ensure that the current instance actually has a
/// value. Accessing this property in the case of a `nil` value is a serious
/// programming error and could lead to undefined behavior or a runtime
/// error.
///
/// In debug builds (`-Onone`), the `unsafelyUnwrapped` property has the same
/// behavior as using the postfix `!` operator and triggers a runtime error
/// if the instance is `nil`.
///
/// The `unsafelyUnwrapped` property is recommended over calling the
/// `unsafeBitCast(_:)` function because the property is more restrictive
/// and because accessing the property still performs checking in debug
/// builds.
///
/// - Warning: This property trades safety for performance. Use
/// `unsafelyUnwrapped` only when you are confident that this instance
/// will never be equal to `nil` and only after you've tried using the
/// postfix `!` operator.
@inlinable public var unsafelyUnwrapped: Wrapped { get }
It is a defined get method. Optionl uses theunsafelyUnwrapped
To get the actual value, for example:
Var ddb: string= "Dongdong"
let ddbCount = ddb.unsafelyUnwrapped.count
This gives the actual value of the variable.
Use of optional
Implement an optional
Let ddb: optional<string> = "Dongdong"
//Var ddb: string= "Dongdong"
The options we implement in this way are actually added after the type of the annotation part?
The implementation is exactly the same.
Optional unpacking
The optional items cannot be used directly. They can only be used after unpacking. Basically, there are the following unpacking methods
-
!
Forced unpacking, for example:
let count = ddb!.count
Before forced unpacking, if you do not know whether it isnil
, you need to perform non nil judgment protection on it first. Otherwise, if the forced unpacking fails, the program will report an error, as shown in the following code:
if ddb != nil {
let count = ddb!.count
print(count)
}
In this way, even if we use forced unpacking, its operation is still safe
-
if
Judge expansion, for example:
if ddb != nil {
let count = ddb?.count
print(count ?? 0)
}
Here we usea ?? b
Merge null operatorsIf there is a value, thencount
, if yesnil
, the default0
There are two conditions for using the merge control operator:
1. expressiona
Must be an optional type
2. expressionb
Must anda
Is the same everywhere
- How to use optional binding
if let ddbStr = ddb {
let count = ddbStr.count
print(count)
}
Use the optional binding to determine whether the optional item has a value. If yes, assign it to a temporary variable. Sameif
The statement can have multiple optional bindings, which can be separated by
Summary
Optional, is an enhanced version of the “non-existent” or “empty” concept. andnil
Is the base version of “does not exist”
Introducing in swiftoptional
The purpose of is to bind the concept of “nonexistence” to specific types.optional.nil
It refers to the “nonexistence” of the value, and indicates that if there is a value, it can only beoptional.some<T>
The value space of all types is extended by nil.