0Pricing
Swift Academy · 课时

通知的 userInfo 载荷

将类型化数据附加到通知中。

通知的 userInfo 载荷 是 CoddyKit 上的免费 Swift Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Swift Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Swift Academy 课程共包含 4 节课。

通知 userInfo

通知可以在其userInfo字典中携带数据,让观察者接收有关所发生事件的详细信息。

使用 userInfo 发布

向post(name:object:userInfo:)传入一个字典。键和值都是Any,因此可以放入任意有效载荷。

import Foundation

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

读取 userInfo

在观察者中读取notification.userInfo,并转换为您所需的值类型。

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])

多个值

字典可以存放多个键,从而将相关数据集中在一起。

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])

类型安全的键

使用字符串字面量作为键容易出错。请定义常量,以避免发布者和观察者之间的键不匹配。

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")

谨慎进行类型转换

由于值的类型是Any,类型转换可能失败。请使用可选绑定,以免类型错误导致崩溃。

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")
}

使用自定义结构体作为有效载荷

您可以将整个结构体存储为一个值,再将其转换回来,从而让有效载荷保持强类型。

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)")
}

封装发布操作

使用一个构建 userInfo 的辅助函数,可以让整个应用中的有效载荷构造保持一致。

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")

封装读取操作

将该辅助函数与类型化访问器配合使用,可以避免观察者重复编写类型转换逻辑。

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)

默认键与缺失键

如果某个键不存在,类型转换会得到 nil。请使用空值合并运算符提供合理的默认值。

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)")

保持有效载荷简洁

userInfo 最适合存放小型、可序列化的数据。对于大型对象,请传递标识符,再由观察者获取其余内容。

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")

快速检查

通知的userInfo字典中存储的值是什么类型?

回顾

userInfo字典以Any值携带通知数据,因此观察者必须谨慎进行类型转换。请使用常量键、辅助函数和类型化访问器,为缺失的键提供默认值,并保持有效载荷简洁。下一步:安全地移除观察者。

常见问题解答

「通知的 userInfo 载荷」课时是免费的吗?

是的 — 「通知的 userInfo 载荷」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Swift Academy 课程的其余内容,请升级到 CoddyKit PRO。 Swift Academy 课程共包含 4 节课。

「通知的 userInfo 载荷」这节课中我会学到什么?

将类型化数据附加到通知中。 你通过在浏览器中直接运行的动手代码来练习 Swift Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Swift Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Swift Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「通知的 userInfo 载荷」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Swift Academy 课中编写并运行代码吗?

能。每节 Swift Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 发布和观察通知
  2. 通知的 userInfo 载荷
  3. 安全移除观察者
  4. 观察者模式的替代方案
← 返回 Swift Academy