NotificationのuserInfoペイロード
型付きデータを通知に付加します。
「NotificationのuserInfoペイロード」はCoddyKit上の無料Swift Academyレッスンです。 これはレッスン2/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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になります。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型の値として通知のデータを保持するため、オブザーバーは慎重にキャストする必要があります。定数キー、ヘルパー関数、型付きアクセサーを使い、存在しないキーにはデフォルト値を指定して、ペイロードは小さく保ちます。次はオブザーバーを安全に削除する方法です。
よくある質問
「NotificationのuserInfoペイロード」レッスンは無料ですか?
はい。「NotificationのuserInfoペイロード」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Swift Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Swift Academyコースには全4レッスンが含まれています。
「NotificationのuserInfoペイロード」で何を学びますか?
型付きデータを通知に付加します。 ブラウザで直接実行するハンズオンコードでSwift Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Swift Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのSwift Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/4です。
「NotificationのuserInfoペイロード」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このSwift Academyレッスンでコードを書いて実行できますか?
はい。すべてのSwift Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- 通知の投稿と監視
- NotificationのuserInfoペイロード
- オブザーバーの安全な削除
- Observerパターンの代替手段