使用泛型簡化陣列函式
通過建立物件導向的刪除功能來擴充套件陣列功能的函式。
// Need to restrict the extension to elements that can be compared.
// The `Element` is the generics name defined by Array for its item types.
// This restriction also gives us access to `index(of:_)` which is also
// defined in an Array extension with `where Element: Equatable`.
public extension Array where Element: Equatable {
/// Removes the given object from the array.
mutating func remove(_ element: Element) {
if let index = self.index(of: element ) {
self.remove(at: index)
} else {
fatalError("Removal error, no such element:\"\(element)\" in array.\n")
}
}
}
用法
var myArray = [1,2,3]
print(myArray)
// Prints [1,2,3]
使用該函式刪除元素而無需索引。只需傳遞要刪除的物件即可。
myArray.remove(2)
print(myArray)
// Prints [1,3]