In swift we deal with optional value . To deal with optional values swift provides us forced unwrapping , optinal binding and optional chaining. Today we discuss forced unwrapping and option binding
Forced Unwrapping : When we use forced wrapping to a variable. It means that we are getting value of it. It cannot be nil.We are ! for forced wrapping.
let myString = "123"
let convertToInt = Int(myString!)
Explanation: Here we know that 123 is in string format and we are converting it into Int value.
Optional Binding: You use optional binding to find out whether an optional contains a value, and if so, to make that value available as a temporary constant or variable. Optional binding can be used with if and while statements to check for a value inside an optional, and to extract that value into a constant or variable, as part of a single action. Lets take the same example.
Example:
let myString = "swift"
let convertToInt = Int(myString)
Output : nil
Its output is nil because we are converting words to Int value.I mean that's not possible. To deal with absence of value we use optional binding.
Optional Binding Syntax :
if let constantName = someOptional {
//statements
}
if let tempValue = convertToInt {
print("converted successfully")
} else {
print("enable to convert")
}
Advantage of Optional Binding
we can avoid crashes in the application in the absence of value.
Forced Unwrapping : When we use forced wrapping to a variable. It means that we are getting value of it. It cannot be nil.We are ! for forced wrapping.
let myString = "123"
let convertToInt = Int(myString!)
Explanation: Here we know that 123 is in string format and we are converting it into Int value.
Optional Binding: You use optional binding to find out whether an optional contains a value, and if so, to make that value available as a temporary constant or variable. Optional binding can be used with if and while statements to check for a value inside an optional, and to extract that value into a constant or variable, as part of a single action. Lets take the same example.
Example:
let myString = "swift"
let convertToInt = Int(myString)
Output : nil
Its output is nil because we are converting words to Int value.I mean that's not possible. To deal with absence of value we use optional binding.
Optional Binding Syntax :
if let constantName = someOptional {
//statements
}
if let tempValue = convertToInt {
print("converted successfully")
} else {
print("enable to convert")
}
Advantage of Optional Binding
we can avoid crashes in the application in the absence of value.
No comments:
Post a Comment