Introduction
Optionals in Swift can hold a value or not hold any value. An Optional is a container that might store a string in it, or it might be empty. It has a lot of extra support built into the language.
Implicit Optional Behavior
The implicit optional behavior is similar to non-optional values. Unwrap techniques are used to handle optional chaining.
- var s : String! = "Hello"
- s?.isEmpty
- if let s = s
- {
- print( s )
- }
- s = nil
- s??"Good"
If Let
The if let statement is used to check if optional values are nonnil and it unwraps the optionals. The type of idx is Int and the idx is a variable within the scope of the statement. The boolean clauses are used together with the if let and the element is not removed when it happened to the first one of the array. Multiple values can be bound to the if statement. The try is used when the data initializer throws an error.
- let urlString = "https://www.websta.unauc.com.png"
- if let url = URL (string : urlString) ,
- let data = try? Data( ContentsOf:url),
- let image = UIImae (data : data)
- {
- let view = UIImageView (image : image)
- PlaygroundPage.current.liveView = view
- }
While let
While let is a loop that terminates when the condition of the loop returns nil. The standard library readline is a function that is used to return an optional string from standard input. While let is used to implement a basic equivalent of Unix cat command. The loop is terminated by adding a clause to detect an empty string. collection protocol provides a make iterator method that returns an iterator and it has the next method.
- var iterator2 = (0..<10). makeIterator ()
- while let i = iterator2.next()
- {
- guard i%2 == 0
- else
- {
- continue
- }
- print(i)
- }
Double Nested Optionals
The type optional wraps can itself be optional, which leads to optionals nested inside optionals. The case-based pattern matching is a way that is used to apply the same rules that work in a switch statement to if statement, for statement, and while statement.
- for case let i? maybeInts
- {
- print (i , teminator : " ")
- }
-
-
-
- for case nil in maybeInts
- {
- print (" Not vales present ")
- }
-
-
- if case 0..<10 = j
- {
- print ("\(j) within range")
- }
Output
5 within range.
If var and while var
The if, while, and for statement is used instead of let statement. This allows us to mutate the variable inside the statement body. Optionals are value types that unwrap the copies from the value inside.
- let number = "1"
- if var i = Int(number)
- {
- i += 1
- print(i)
- }
Unwrapped Optionals
The first property returns an optional of the first element, or nil when the array is empty. The optional have to unwrap in order to use it. The unwrapped value is present inside the if let block. The compiler checks the code to confirm the two possible paths in which the function returns the period.
- extension String
- {
- var fileExtension : String?
- {
- let period : String.Index
- if let idx = lastIndex (of : ".")
- {
- period = idx
- }
- else
- {
- return nil
- }
- let extensionStart = index (after : period)
- return String (self [ extensionStart ])
- }
- }
Optional Chaining
Sending a message to nil is a no-op and it is implemented by the optional chaining and when the method is called by optional chaining it returns a result, and the result is optional. The result is optional when the optional chaining returns a result. The didChange property stores the callback function and the text field is called when the user edits the text.
- func textDidChange(newText: String) {
- text = newText
- didChange ? (text)
- }
- }