LoginSignup
10
9

More than 5 years have passed since last update.

[Swift]タプルの配列

Last updated at Posted at 2015-09-08
tuple
    override func viewDidLoad() {
        super.viewDidLoad()

        let texts: [(rare: Int, name: String)] = [
            (5,"三日月宗近"),
            (3,"小狐丸"),
            (3,"石切丸"),
            (3,"岩融"),
            (1,"今剣")]

        // 要素へのアクセス例
        println(texts[0].name)  // 三日月宗近
        println(texts[4].rare)  // 1
    }

TableViewでの応用

tableView
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")

        // セルのテキストはタプルのnameをセット
        cell.textLabel?.text = texts[indexPath.row].name

        // セルの背景色はタプルのrareから判定してセット        
        switch (texts[indexPath.row].rare)
        {
        case 1:
            cell.backgroundColor = UIColor.whiteColor();
            break
        case 2:
            cell.backgroundColor = UIColor.blueColor();
            break
        case 3:
            cell.backgroundColor = UIColor.greenColor();
            break
        case 4:
            cell.backgroundColor = UIColor.orangeColor();
            break
        case 5:
            cell.backgroundColor = UIColor.magentaColor();
            break
        default:
            break
        }

        return cell
    }

実施例
iOS Simulator-3.jpg

参考ソース
https://github.com/senseiswift/tableviewtest/commit/29f759d2220972b7c0f980d7f1181a54a56804ed

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