使用泛型简化数组函数
通过创建面向对象的删除功能来扩展数组功能的函数。
// 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]