2/05/2024

SWIFT Examples of Initializing and Forcefully Unwrapping Optionals

 String

var nonOptionalString: String = "Hello"
print(nonOptionalString) // Directly prints "Hello"

var optionalString: String? = "Hello"
print(optionalString!) // Forcefully unwraps and prints "Hello"

.

String optional

var optionalString: String? = "Hello"
if let unwrappedString = optionalString {
print(unwrappedString) // Prints "Hello"
} else {
print("optionalString was nil")
}

optionalString = nil
if let unwrappedString = optionalString {
print(unwrappedString)
} else {
print("optionalString was nil") // Prints "optionalString was nil" because it's now nil
}

.


Int

var nonOptionalInt: Int = 4
print(nonOptionalInt) // Directly prints 4

var optionalInt: Int? = 4
print(optionalInt!) // Forcefully unwraps and prints 4

.


Int optional

var optionalInt: Int? = 4
if let unwrappedInt = optionalInt {
print(unwrappedInt) // Prints 4
} else {
print("optionalInt was nil")
}

optionalInt = nil
if let unwrappedInt = optionalInt {
print(unwrappedInt)
} else {
print("optionalInt was nil") // Prints "optionalInt was nil" because it's now nil
}

.


Float

var nonOptionalFloat: Float = 3.14
print(nonOptionalFloat) // Directly prints 3.14

var optionalFloat: Float? = 3.14
print(optionalFloat!) // Forcefully unwraps and prints 3.14

.


Double

var nonOptionalDouble: Double = 3.14159
print(nonOptionalDouble) // Directly prints 3.14159

var optionalDouble: Double? = 3.14159
print(optionalDouble!) // Forcefully unwraps and prints 3.14159

.


Bool

var nonOptionalBool: Bool = true
print(nonOptionalBool) // Directly prints true

var optionalBool: Bool? = true
print(optionalBool!) // Forcefully unwraps and prints true

.


optional type is added '?' in the end of type.

so that the value can be have "nil". "nil" is also classified false in if logic.

The reason why exist such a type is swift is UI based language and value from ui button or action might have any value, so to prevent error, optional type would be needed. 


πŸ™‡πŸ»‍♂️



No comments:

Post a Comment