Get next or previous item to an object in a Swift collection or array

Viewed 9321

What is the best way to identify the item that precedes or follows a specified object in a Swift array, while protecting against out of bounds errors?

4 Answers

Why not use Swift's factory methods?

try this to get a previous item to an object.

                let currentIndex = yourArr.index(of: "0")
                let previousVal = yourArr[currentIndex-1]

First get the index of object you want previous item for, then get the item of that index-1.

import UIKit

extension Array where Element : Equatable {

/// Finds next element of the array, returns nil if there is no next element
func nextElement(element: Element, completion: @escaping(Element?)->()){
    let currentIndex = self.firstIndex { $0 == element}
    if let currIndex = currentIndex?.advanced(by: 1) {
        completion(currIndex >= self.endIndex ? nil : self[currIndex])
    }else{
        completion(nil)
    }
}

/// Finds prev element of the array, returns nil if there is no previous element
func prevElement(element: Element, completion: @escaping(Element?)->()){
    let currentIndex = self.firstIndex { $0 == element}
    if let currIndex = currentIndex?.advanced(by: -1) {
        completion(currIndex <= self.endIndex ? nil : self[currIndex])
    }else{
        completion(nil)
    }
}

}

Related