Skip to content

Latest commit

 

History

History
67 lines (54 loc) · 1.71 KB

Array.md

File metadata and controls

67 lines (54 loc) · 1.71 KB

#Remove element
#Last index
#Last index with predicate
#Last index of an Element
#Is not empty

This is extension for Array where Element: Equatable

extension Array where Element: Equatable {
    mutating func remove (element: Element) {
        if let i = self.index(of: element) {
            self.remove(at: i)
        }
    }
}
var lastIndex: Int {
        return count - 1
    }

Example: yourArray.lastIndex(where: { $0 == "Swift" })

func lastIndex(where predicate: (Element) throws -> Bool) rethrows -> Int? {
        for i in (0..<count).reversed() {
            if try predicate(self[i]) {
                return i
            }
        }
        return nil
    }

This is extension for Array where Element: Equatable

extension Array where Element: Equatable {
    func lastIndex(of element: Element) -> Int? {
        for i in (0..<count).reversed() {
            if element == self[i] {
                return i
            }
        }
        return nil
    }
}
var isNotEmpty: Bool {
        return !isEmpty
    }