LoginSignup
9
10

More than 5 years have passed since last update.

Swiftで関数を配列にまとめる

Last updated at Posted at 2014-10-17

関数を配列に

UITalbeViewを使用してサンプルを作成しました。
要はメソッドを定義して、それを配列にまとめるやり方です。

処理の流れ

  • TableViewの各セルに個別の関数を用意する
  • メソッドをまとめた配列を設定する
  • セル選択時に配列から関数を実行させる

画面はこんな感じ。
スクリーンショット 2014-10-17 12.29.14.png

サンプルソース

TableViewActionController.swift
import UIKit

class TableViewActionController : UITableViewController {

    var actionMap: [[Void -> Void]] {
        return [
            // Section1
            [
                self.cell1_1,
                self.cell1_2,
                self.cell1_3
            ],
            // Section2
            [
                self.cell2_1,
                self.cell2_2
            ]
        ]
    }

    func cell1_1() {
        println("cell1_1");
    }

    func cell1_2() {
        println("cell1_2");
    }

    func cell1_3() {
        println("cell1_3");
    }

    func cell2_1() {
        println("cell2_1");
    }

    func cell2_2() {
        println("cell2_2");
    }

    // MARK: UITableViewDelegate

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let action = actionMap[indexPath.section][indexPath.row]
        action()
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }
}

普通ならdidSelectRowAtIndexPathでif文を使って、セクションと行を判断して...ってやるんだけど、とても簡潔に記述できました。
prepareForSegueとかにも応用できそうです。

9
10
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
9
10