PassKit PassKit - 4 months ago 20
iOS Question

How to access NSIndexPath section value?

I cannot understand why in the following code,

is retuning a null value.

override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell? {
NSLog("Index Path %@", indexPath)
// Index Path <NSIndexPath: 0x1666d1d0> {length = 2, path = 0 - 0}

NSLog("Index Path Section %@", indexPath.section)
// Index Path Section (null)

Following this question I have also tried the following to access the section value:

if let section = indexPath?.section {
NSLog("Index Path Section %@", section)

I have a table with 2 sections with 1 row in each section. On the first iteration where
path = 0 - 0
, the log shows
Index Path Section (null)
. On the second iteration where
path = 1 - 0
the program crashes.

I'm not trying to do anything complicated, I just need to access the section value so that I can conditionally return the correct type of cell.


You are access the section value correctly. You are just print it the wrong way.

section have type of NSInteger, which is Int in swift

just change log to NSLog("Index Path Section %d", indexPath.section)

It print (null) because the section value is 0. and crashed when it is 1 because it is not valid object pointer