View postDeclarationExample.swift
func post(name aName: Notification.Name, | |
object anObject: Any?, | |
userInfo aUserInfo: [AnyHashable : Any]? = nil) |
View PostExample.swift
let center = NotificationCenter.default | |
let notificationReceived = Notification.Name("notificationReceived") | |
let pizzas = ["Margherita": 1, "Pepperoni": 16, "Hawaii": 25] | |
center.post(name: notificationReceived, object: self, userInfo: pizzas) |
View addObserverExample.swift
let center = NotificationCenter.default | |
center.addObserver(self, | |
selector: #selector(onNotificationReceived(_:)), | |
name: .notificationReceived, | |
object: nil) | |
@objc func onNotificationReceived(_ notification:Notification) { | |
if let data = notification.userInfo as? [String: Int] { | |
// Do something with the data | |
} |
View addObserverDeclarationExample.swift
func addObserver(_ observer: Any, | |
selector aSelector: Selector, | |
name aName: Notification.Name?, | |
object anObject: Any?) |
View OptionalBindingUsingGuardLet.swift
let myOptional: Int? = 10 | |
guard let myInt = myOptional else { | |
print("myInt has no value.") | |
} | |
print("myInt has a value of \(myInt).") |
View OptionalChaining.swift
struct Processor { | |
var modelNumber: Int | |
init() { | |
self.modelNumber = 21043 | |
} | |
} | |
struct Computer { | |
var processor: Processor? | |
init(processor: Processor?) { |
View NilCoalescing.swift
let myOptional: Int? = nil | |
let myInt = myOptional ?? 0 | |
print("myInt has a value of \(myInt).") |
View OptionalBindingUsingMultipleIfLet.swift
let myFirstOptional: Int? = 10 | |
let mySecondOptional: Int? = 20 | |
if let myFirstInt = myFirstOptional, let mySecondInt = mySecondOptional { | |
print("myFirstInt has a value of \(myFirstInt) and mySecondInt has a value of \(mySecondInt).") | |
} |
View OptionalBindingUsingIfLet.swift
let myOptional: Int? = 10 | |
if let myInt = myOptional { | |
print("myInt has a value of \(myInt).") | |
} |
View ForceUnwrapping.swift
let myOptional: Int? = 10 | |
print("myOptional has a value of \(myOptional!).") |