0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[初学者向け]意外と難しいSwiftのデリゲートについて

Posted at

はじめに

Swiftでアプリを開発していると「デリゲート(Delegate)」という概念を目にすることが多いです。デリゲートは、オブジェクト間の通信をスムーズに行うためのデザインパターンで、特にUIKitの開発でよく使われます。

学習内容の整理も兼ねて、デリゲートの基本概念とシンプルなサンプルコードを使って初心者向けに解説します。


デリゲートとは?

デリゲートとは、あるオブジェクトの処理を他のオブジェクトに委譲する仕組みのことです。主に以下の場面で使われます。

  • テーブルビュー(UITableViewDelegate)
  • テキストフィールドの入力管理(UITextFieldDelegate)
  • カスタムクラス間のデータ受け渡し

デリゲートを使うことで、以下のメリットがあります。

  • クラス間の結合度を下げることができる
  • コードの再利用性が向上する
  • シンプルで直感的なイベント管理が可能

デリゲートの基本実装

1.プロトコルを定義する

protocol SampleDelegate: AnyObject {
    func didUpdateMessage(_ message: String)
}

2.デリゲートを持つクラス(委譲元)を作成

class Sender {
    weak var delegate: SampleDelegate?
    
    func sendMessage() {
        let message = "Hello from Sender!"
        delegate?.didUpdateMessage(message)
    }
}

3.デリゲートを受け取るクラス(委譲先)を作成

class Receiver: SampleDelegate {
    func didUpdateMessage(_ message: String) {
        print("Received message: \(message)")
    }
}

4.デリゲートをセットして動作を確認

let sender = Sender()
let receiver = Receiver()

sender.delegate = receiver
sender.sendMessage()

実行結果

Received message: Hello from Sender!

まとめ

項目 内容
デリゲートとは? 他のクラスに処理を委譲する仕組み
メリット クラス間の結合度を下げ、再利用性を高める
実装の手順 ①プロトコル定義 ②委譲元クラス ③委譲先クラス ④デリゲート設定

デリゲートはUIKit開発で頻繁に使用される重要なパターンです。
基本を理解すれば、Swift開発の幅が大きく広がるので、ぜひ試してみてください!

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?