Optionals:
which handles the absence of a value.
Ex: var perhapsStr: String?
The above declaration is equivalent to explicitly initializing it to nil which means no value −
var perhapsStr: String? = nil
var myString:String? = nil
if myString != nil {
print(myString)
} else {
print("myString has nil value")
}
Forced Unwrapping : just means putting an exclamation mark at the end of the variable.
Automatic Unwrapping : You can declare optional variables using exclamation mark instead of a question mark.
Optional Binding : Use optional binding to find out whether an optional contains a value , and to make that value available as a temporary constant or variable.
Ex:
if let constantName = someOptional {
statements
}
var myString:String?
myString = "Hello, Swift 4!"
if let yourString = myString {
print("Your string has - \(yourString)")
} else {
print("Your string does not have a value")
}
Output : Your string has - Hello, Swift 4!
No comments:
Post a Comment