Skip to content

Instantly share code, notes, and snippets.

View andreaslydemann's full-sized avatar

Andreas Lüdemann andreaslydemann

View GitHub Profile
let myOptional: Int? = 10
if let myInt = myOptional {
print("myInt has a value of \(myInt).")
}
let myOptional: Int? = nil
let myInt = myOptional ?? 0
print("myInt has a value of \(myInt).")
let myOptional: Int? = 10
print("myOptional has a value of \(myOptional!).")
let myOptional: Int? = 10
guard let myInt = myOptional else {
print("myInt has no value.")
}
print("myInt has a value of \(myInt).")
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).")
}
struct Processor {
var modelNumber: Int
init() {
self.modelNumber = 21043
}
}
struct Computer {
var processor: Processor?
init(processor: Processor?) {
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
}
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)
func post(name aName: Notification.Name,
object anObject: Any?,
userInfo aUserInfo: [AnyHashable : Any]? = nil)
func addObserver(_ observer: Any,
selector aSelector: Selector,
name aName: Notification.Name?,
object anObject: Any?)