Skip to content

Instantly share code, notes, and snippets.

Avatar

Andreas Lüdemann andreaslydemann

View GitHub Profile
View ForceUnwrapping.swift
let myOptional: Int? = 10
print("myOptional has a value of \(myOptional!).")
View OptionalBindingUsingIfLet.swift
let myOptional: Int? = 10
if let myInt = myOptional {
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 NilCoalescing.swift
let myOptional: Int? = nil
let myInt = myOptional ?? 0
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 OptionalBindingUsingGuardLet.swift
let myOptional: Int? = 10
guard let myInt = myOptional else {
print("myInt has no value.")
}
print("myInt has a value of \(myInt).")
View addObserverDeclarationExample.swift
func addObserver(_ observer: Any,
selector aSelector: Selector,
name aName: Notification.Name?,
object anObject: Any?)
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 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 postDeclarationExample.swift
func post(name aName: Notification.Name,
object anObject: Any?,
userInfo aUserInfo: [AnyHashable : Any]? = nil)