PassKit PassKit - 1 year ago 102
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.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download