Swift3 自作デリゲート実装
ショップにアイテムが正常に追加、削除された場合のみ通知されるデリゲートを作る。
- すでにあるアイテムの追加は無効
- 存在しないアイテムの削除は無効
ShopNotify.swift
protocol ShopNotify { func shopNotify(addItem item: String) func shopNotify(removeItem item: String) } class Shop { var delegate: ShopNotify? var items: [String] = [] func addItem(_ item: String) { if items.index(of: item) == nil { items.append(item) delegate?.shopNotify(addItem: item) } } func removeItem(_ item: String) { guard let index = items.index(of: item) else { return } items.remove(at: index) delegate?.shopNotify(removeItem: item) } }
ViewController.swift
import UIKit class ViewController: UIViewController, ShopNotify { // 通知 func shopNotify(addItem item: String) { print("「\(item)」 が追加されました") } func shopNotify(removeItem item: String) { print("「\(item)」 が削除されました") } override func viewDidLoad() { super.viewDidLoad() let shop = Shop() shop.delegate = self shop.addItem("鉄の斧") shop.addItem("世界樹の葉") shop.addItem("世界樹の葉") shop.removeItem("鉄の斧") shop.removeItem("紫の炎") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
「鉄の斧」 が追加されました 「世界樹の葉」 が追加されました 「鉄の斧」 が削除されました