Created
December 11, 2014 14:55
-
-
Save aspitz/796c442c7e023598e588 to your computer and use it in GitHub Desktop.
A Table data structure to support UITableView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Table<valueType:Equatable>{ | |
var table:[[valueType]] = [[valueType]]() | |
var sectionCount:Int{ | |
get{ | |
return table.count | |
} | |
} | |
subscript(section:Int) -> [valueType]?{ | |
get{ | |
var sectionArray:[valueType]? | |
if (section < sectionCount){ | |
sectionArray = table[section] | |
} | |
return sectionArray | |
} | |
} | |
subscript(indexPath:NSIndexPath) -> valueType?{ | |
get{ | |
var value:valueType? | |
if let section = self[indexPath.section]{ | |
if section.count > indexPath.row { | |
value = section[indexPath.row] | |
} | |
} | |
return value | |
} | |
mutating set{ | |
if var section = self[indexPath.section]{ | |
if section.count > indexPath.row { | |
table[indexPath.section][indexPath.row] = newValue! | |
} | |
} | |
} | |
} | |
subscript(indexPath:(forRow:Int,inSection:Int)) -> valueType?{ | |
get{ | |
return self[NSIndexPath(forRow: indexPath.forRow, inSection: indexPath.inSection)] | |
} | |
mutating set{ | |
self[NSIndexPath(forRow: indexPath.forRow, inSection: indexPath.inSection)] = newValue | |
} | |
} | |
mutating func add(value:valueType, toSection section:Int = 0){ | |
if (section >= sectionCount){ | |
for index in (sectionCount...section){ | |
table.append([valueType]()) | |
} | |
} | |
table[section].append(value) | |
} | |
mutating func insert(value:valueType, inRow row:Int, section:Int = 0){ | |
table[section].insert(value, atIndex: row) | |
} | |
mutating func remove(atRow row:Int, inSection section:Int = 0){ | |
table[section].removeAtIndex(row) | |
} | |
mutating func removeSection(section:Int){ | |
table.removeAtIndex(section) | |
} | |
func indexPathOf(value:valueType, inSection:Int? = nil) -> NSIndexPath?{ | |
var indexPath:NSIndexPath? | |
if let section = inSection { | |
if let row = find(table[section], value){ | |
indexPath = NSIndexPath(forRow: row, inSection: section) | |
} | |
} else { | |
for (section, sectionArray) in enumerate(table){ | |
if let row = find(sectionArray, value){ | |
indexPath = NSIndexPath(forRow: row, inSection: section) | |
} | |
} | |
} | |
return indexPath | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment