回答編集履歴

1

中央値を取る方法

2017/04/19 02:03

投稿

fuzzball
fuzzball

スコア16731

test CHANGED
@@ -19,3 +19,155 @@
19
19
  ]
20
20
 
21
21
  ```
22
+
23
+
24
+
25
+ # 中央値を取る方法
26
+
27
+
28
+
29
+ Swift2の丸投げコードです。
30
+
31
+ セルはRight Detailで。
32
+
33
+
34
+
35
+ ```swift
36
+
37
+ class TableViewController: UITableViewController {
38
+
39
+
40
+
41
+ var array = [
42
+
43
+ ["id": 0, "order": 2.0, "name": "猫"],
44
+
45
+ ["id": 1, "order": 0.0, "name": "犬"],
46
+
47
+ ["id": 2, "order": 4.0, "name": "猿"],
48
+
49
+ ["id": 3, "order": 1.0, "name": "キジ"],
50
+
51
+ ["id": 4, "order": 3.0, "name": "トラ"],
52
+
53
+ ]
54
+
55
+
56
+
57
+ override func viewDidLoad() {
58
+
59
+ super.viewDidLoad()
60
+
61
+ self.navigationItem.rightBarButtonItem = self.editButtonItem()
62
+
63
+ self.sortArray()
64
+
65
+ }
66
+
67
+
68
+
69
+ func sortArray() {
70
+
71
+ array = array.sort{($0["order"] as! Double) < ($1["order"] as! Double)}
72
+
73
+ }
74
+
75
+
76
+
77
+ override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
78
+
79
+ return array.count
80
+
81
+ }
82
+
83
+
84
+
85
+ override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
86
+
87
+ let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
88
+
89
+ let obj = array[indexPath.row]
90
+
91
+ cell.detailTextLabel!.text = "\(obj["order"]!)"
92
+
93
+ cell.textLabel!.text = obj["name"] as? String
94
+
95
+ return cell
96
+
97
+ }
98
+
99
+
100
+
101
+ override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
102
+
103
+
104
+
105
+ print("from \(fromIndexPath.row) to \(toIndexPath.row)")
106
+
107
+
108
+
109
+ if fromIndexPath.row == toIndexPath.row {
110
+
111
+ print("skip")
112
+
113
+ } else {
114
+
115
+ var newOrder: Double
116
+
117
+ if toIndexPath.row == 0 {
118
+
119
+ //一番上に移動した場合は先頭セル - 1
120
+
121
+ newOrder = (array[toIndexPath.row]["order"] as! Double) - 1.0
122
+
123
+ } else if toIndexPath.row == array.count - 1 {
124
+
125
+ //一番下に移動した場合は末尾セル + 1
126
+
127
+ newOrder = (array[toIndexPath.row]["order"] as! Double) + 1.0
128
+
129
+ } else {
130
+
131
+ //途中に移動したときは上下セルの中央値
132
+
133
+ var rowPrev: Int, rowNext: Int;
134
+
135
+ if (toIndexPath.row < fromIndexPath.row) {
136
+
137
+ //上に移動した場合
138
+
139
+ rowPrev = toIndexPath.row - 1
140
+
141
+ rowNext = toIndexPath.row
142
+
143
+ } else {
144
+
145
+ //下に移動した場合
146
+
147
+ rowPrev = toIndexPath.row
148
+
149
+ rowNext = toIndexPath.row + 1
150
+
151
+ }
152
+
153
+ newOrder = ((array[rowPrev]["order"] as! Double) + (array[rowNext]["order"] as! Double)) / 2.0
154
+
155
+ }
156
+
157
+ array[fromIndexPath.row]["order"] = newOrder
158
+
159
+
160
+
161
+ self.sortArray()
162
+
163
+ tableView.reloadData()
164
+
165
+ }
166
+
167
+ }
168
+
169
+ }
170
+
171
+ ```
172
+
173
+