Created
December 8, 2022 00:36
-
-
Save navczydev/464bd61e50a052704b4c2d5e9e9ea3a8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
var name:String? = "Swift" | |
// force un-wrap | |
print("Name is \(name!)") | |
name = nil | |
// nil coalescing operator ?? | |
print("Name is ??: \(name ?? "Swift")") | |
// Check for optional using the if statement | |
if name != nil { | |
// Swift is not smart enough here to inference the type of name. | |
// name is still optional here 🤯 | |
print("Name is \(name ?? "Swift")") | |
}else{ | |
print("Name is nil") | |
} | |
// Optional binding(if let) | |
if let name = name{ | |
// Here the type of name is String | |
print("Safe value received: \(name)") | |
}else{ | |
print("Name is still null") | |
} | |
// Chaining object | |
struct Language{ | |
let name:String | |
} | |
// Optional object | |
var swift:Language? = Language(name: "Swift") | |
// Note here object is nullable not its property | |
print("Language name:\(swift?.name ?? "Swift")") | |
// guard let | |
func getFormattedName(name: String?) -> String{ | |
guard let name = name else { | |
// fallback name | |
return "No name found" | |
} | |
// only executes if name is not nil | |
return "Nmae is: \(name)" | |
} | |
print("Formatted name: \(getFormattedName(name: nil))") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment