Now that we've learned about the Optional
*** Optional (Wrapped) In a nutshell, a type that represents either a value or an empty type. *** *** Basically, swift variables and constants basically do not allow nil, but when using that nil *** Use Optional (Wrapped) type! ***
For example
qiita.rbvar
1.var n: Int
2.
3.print(n)//error
As mentioned above, an error will occur if you try to output a value that does not exist. That's where the Optional (Wrapped) type comes in.
qiita.rbvar
1.var n: Optional<Int>
2.
3.print(n)//nil
As mentioned above, if you use the Optional (Wrapped) type, no error will occur and nil will be output.
In this way, an error occurs because the behavior is *** "If you wrap the data with" Optional type "***, " nil " will be returned if the value does not exist." Can be avoided. This is the basic usage of *** "Optional type" ***.
Optional (Wrapped) types may not have values, so they cannot be treated in the same way as Wrapped type variables and constants. For example, Int? Four arithmetic operations between types will result in an error.
qiita.rbvar
1.let a: Int? = 1
2.let b: Int? = 1
3.a+b//error
Unwrap to avoid this error. There are three ways to unwrap.
○ *** Optional binding *** ○ ? ?? operator ○ *** Forced unwrap ***
Let's dig deep one by one!
qiita.rbvar
if let constant name= Optional(Wrapped)Type{
//Statement executed if the value exists
}
As in the above statement, if you use an if-let statement and have a Wrapped type value, the {} statement is executed. In the following example, since the constant A has a value, the value is assigned to the constant a of type String and the executable statement is executed!
qiita.rbvar
1.let A: Optional("1") //Int type
2.if let A {
print(type(of:1))
//Execution result: Int
}
In the following example ,? ?? String type with the String type value "a" on the left side of the operator? The constant optionalString of is specified as the String type value "b" on the right side, and as a result, the value "a" on the left side is acquired.
qiita.rbvar
1.let optionalString:String? = "a"
2.if String = optionalString ?? "b"
//Execution result a
Forced unwrap is a method of forcibly extracting the value of Wrapped type from Optional (Wrapped) type. To do a forced unwrap! Use the operator. I mentioned above that you can't treat it like a Wrapped variable or constant, but you can retrieve it by using forced unwrap.
qiita.rbvar
let a : Int? = 1
let b : Int? = 1
a!+b! = //2
Recommended Posts