Search code examples
iosswiftnsindexpath

SWIFT - Create/Change NSIndexPath with length equal to 1


So right now, the indexPath length is 2. Is there a way that I can change it to 1? Will I have to create a different NSIndexPath manually with the length 1? If so, how would I go about doing it.

Thanks in advance


Solution

  • You will have to create a new NSIndexPath. If you need to remove a specific value you must play with pointers in Swift

    let originalPath = NSIndexPath(indexes: [1,2,3], length: 3)
    var indexes = UnsafeMutablePointer<Int>.alloc(originalPath.length)
    originalPath.getIndexes(indexes) // This extracts values from NSIndexPath
    
    var newValues = Array<Int>()
    // Iterate over the pointer array
    for val in UnsafeBufferPointer(start: indexes, count: originalPath.length) {
        // Determine values which you want in the new NSIndexPath
        newValues.append(val)
    }
    
    let newPath = NSIndexPath(indexes: newValues, length: newValues.count)