Xcode 8.2 • Swift 3.0.2
var k = [true, true, true, false, true, false]
if let index = k.reversed().index(of: true) {
k.remove(at: index.base - 1)
}
print(k) // "[true, true, true, false, false]"
If you would like to create an extension to add this functionality to Array you need to constrain it to equatable elements:
extension Array where Element: Equatable {
/// Returns the last index where the specified value appears in the collection.
/// After using lastIndex(of:) to find the last position of a particular element in a collection, you can use it to access the element by subscripting.
/// - Parameter element: The element to find the last Index
func lastIndex(of element: Element) -> Index? {
if let index = reversed().index(of: element) {
return index.base - 1
}
return nil
}
/// Removes the last occurrence where the specified value appears in the collection.
/// - Returns: True if the last occurrence element was found and removed or false if not.
/// - Parameter element: The element to remove the last occurrence.
@discardableResult
mutating func removeLastOccurrence(of element: Element) -> Bool {
if let index = lastIndex(of: element) {
remove(at: index)
return true
}
return false
}
}
Playground testing
var k = [true, true, true, false, true, false]
k.removeLastOccurrence(of: true)
print(k) // "[true, true, true, false, false]"