0Pricing
Swift Academy · Lesson

Notification userInfo Payloads

Attach typed data to notifications.

Notification userInfo Payloads is a free Swift Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Notification userInfo

A notification can carry data in its userInfo dictionary, letting observers receive details about what happened.

Posting with userInfo

Pass a dictionary to post(name:object:userInfo:). Keys and values are Any, so any payload fits.

import Foundation

let center = NotificationCenter.default
let name = Notification.Name("scoreChanged")
center.post(name: name, object: nil, userInfo: ["score": 100])
print("Posted with payload")

Reading userInfo

In the observer, read notification.userInfo and cast the value you expect.

import Foundation

let center = NotificationCenter.default
let name = Notification.Name("scoreChanged")
_ = center.addObserver(forName: name, object: nil, queue: nil) { note in
    if let score = note.userInfo?["score"] as? Int {
        print("Score: \(score)")
    }
}
center.post(name: name, object: nil, userInfo: ["score": 42])

Multiple Values

The dictionary can hold several keys, packaging related data together.

import Foundation

let center = NotificationCenter.default
let name = Notification.Name("login")
_ = center.addObserver(forName: name, object: nil, queue: nil) { note in
    let user = note.userInfo?["user"] as? String ?? "?"
    let admin = note.userInfo?["admin"] as? Bool ?? false
    print("\(user) admin=\(admin)")
}
center.post(name: name, object: nil, userInfo: ["user": "ada", "admin": true])

Type-Safe Keys

Using string-literal keys is error-prone. Define constants to avoid mismatches between poster and observer.

import Foundation

enum Keys { static let amount = "amount" }
let center = NotificationCenter.default
let name = Notification.Name("purchase")
center.post(name: name, object: nil, userInfo: [Keys.amount: 9.99])
print("Used a constant key")

Casting Carefully

Because values are Any, casts can fail. Use optional binding so a wrong type does not crash.

import Foundation

let note = Notification(name: Notification.Name("x"), object: nil, userInfo: ["n": "oops"])
if let n = note.userInfo?["n"] as? Int {
    print(n)
} else {
    print("Wrong type, handled safely")
}

Custom Structs as Payload

You can store a whole struct as a value and cast it back, keeping payloads strongly typed.

import Foundation

struct Event { let id: Int }
let note = Notification(name: Notification.Name("e"), object: nil, userInfo: ["event": Event(id: 7)])
if let e = note.userInfo?["event"] as? Event {
    print("Event id: \(e.id)")
}

Wrapping the Post

A helper function that builds the userInfo keeps payload construction consistent across the app.

import Foundation

let name = Notification.Name("progress")
func postProgress(_ value: Int) {
    NotificationCenter.default.post(name: name, object: nil, userInfo: ["value": value])
}
postProgress(75)
print("Posted progress")

Wrapping the Read

Pair the helper with a typed accessor so observers do not repeat casting logic.

import Foundation

extension Notification {
    var progressValue: Int? { userInfo?["value"] as? Int }
}
let n = Notification(name: Notification.Name("progress"), object: nil, userInfo: ["value": 50])
print(n.progressValue ?? -1)

Default vs Missing Keys

If a key is absent, the cast yields nil. Provide a sensible default with the nil-coalescing operator.

import Foundation

let n = Notification(name: Notification.Name("y"), object: nil, userInfo: [:])
let count = n.userInfo?["count"] as? Int ?? 0
print("Count defaulted to \(count)")

Keep Payloads Small

userInfo is best for small, serializable data. For large objects, pass an identifier and let observers fetch the rest.

import Foundation

let name = Notification.Name("itemUpdated")
// Send just an id, not a heavy object graph.
NotificationCenter.default.post(name: name, object: nil, userInfo: ["id": 1234])
print("Posted a lightweight payload")

Quick Check

What type are the values stored in a notification's userInfo dictionary?

Recap

The userInfo dictionary carries notification data as Any values, so observers cast carefully. Use constant keys, helper functions, and typed accessors, default missing keys, and keep payloads small. Next: removing observers safely.

Frequently asked questions

Is the “Notification userInfo Payloads” lesson free?

Yes — the full text of “Notification userInfo Payloads” is free to read here on the web, and the Swift Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.

What will I learn in “Notification userInfo Payloads”?

Attach typed data to notifications. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Notification userInfo Payloads” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Posting and Observing Notifications
  2. Notification userInfo Payloads
  3. Removing Observers Safely
  4. The Observer Pattern Alternatives
← Back to Swift Academy