3 回答
TA貢獻1812條經驗 獲得超5個贊
removeObject()RangeReplaceableCollectionTypeArrayEquatable:
extension RangeReplaceableCollectionType where Generator.Element : Equatable {
// Remove first collection element that is equal to the given `object`: mutating func removeObject(object : Generator.Element) {
if let index = self.indexOf(object) {
self.removeAtIndex(index)
}
}}var ar = [1, 2, 3, 2]ar.removeObject(2)print(ar) // [1, 3, 2]
Array:
extension Array where Element : Equatable {
// ... same method as above ...}extension Array where Element: Equatable {
// Remove first collection element that is equal to the given `object`: mutating func remove(object: Element) {
if let index = index(of: object) {
remove(at: index)
}
}}TA貢獻1811條經驗 獲得超4個贊
注
'T' is not convertible to 'T'
'AnyObject' is not convertible to 'T'
func removeObject<T : Equatable>(object: T, inout fromArray array: [T]) {}func arrayRemovingObject<T : Equatable>(object: T, fromArray array: [T]) -> [T] {}extension Array {
mutating func removeObject<U: Equatable>(object: U) {
var index: Int?
for (idx, objectToCompare) in enumerate(self) {
if let to = objectToCompare as? U {
if object == to {
index = idx }
}
}
if(index != nil) {
self.removeAtIndex(index!)
}
}}var list = [1,2,3]list.removeObject(2) // Successfully removes 2 because types matchedlist.removeObject("3") // fails silently to remove anything because the types don't matchlist // [1, 3]編輯
extension Array {
mutating func removeObject<U: Equatable>(object: U) -> Bool {
for (idx, objectToCompare) in self.enumerate() { //in old swift use enumerate(self)
if let to = objectToCompare as? U {
if object == to {
self.removeAtIndex(idx)
return true
}
}
}
return false
}}var list = [1,2,3,2]list.removeObject(2)list
list.removeObject(2)listTA貢獻1911條經驗 獲得超7個贊
func removeObject<T : Equatable>(object: T, inout fromArray array: [T]) {
var index = find(array, object)
array.removeAtIndex(index!)}- 3 回答
- 0 關注
- 601 瀏覽
添加回答
舉報
