Swift2: Array extension to remove object by value - Foundation
PFUser
does not conform to Equatable
protocol so your extension doesn't apply. But a PFUser
is identified through its user name. You can solve your problem with filter
, no extension required:
func cell(cell: FriendSearchTableViewCell, didSelectUnfollowUser user: PFUser) {
if var followers = followingUsers {
ParseHelper.removeFollowRelationshipFromUser(PFUser.currentUser()!, toUser: user)
// update local cache
followers = followers.filter { $0.username != user.username }
self.followingUsers = followers
}
}
Removing object from array in Swift 3
The Swift equivalent to NSMutableArray
's removeObject
is:
var array = ["alpha", "beta", "gamma"]
if let index = array.firstIndex(of: "beta") {
array.remove(at: index)
}
if the objects are unique. There is no need at all to cast to NSArray
and use indexOfObject:
The API index(of:
also works but this causes an unnecessary implicit bridge cast to NSArray
.
Of course you can write an extension of RangeReplaceableCollection
to emulate the function. But due to value semantics you cannot name it removeObject
.
extension RangeReplaceableCollection where Element : Equatable {
@discardableResult
mutating func remove(_ element : Element) -> Element?
{
if let index = firstIndex(of: element) {
return remove(at: index)
}
return nil
}
}
Like remove(at:
it returns the removed item or nil
if the array doesn't contain the item.
If there are multiple occurrences of the same object use filter
. However in cases like data source arrays where an index is associated with a particular object firstIndex(of
is preferable because it's faster than filter
.
Update:
In Swift 4.2+ you can remove one or multiple occurrences of beta
with removeAll(where:)
:
array.removeAll{$0 == "beta"}
What is the better way to remove object in swift Array
There is no convenient method in the Foundation. But we can extend Array structure with needed one. Consider this:
extension Array where Element: Equatable {
mutating func remove(object: Element) {
if let index = index(of: object) {
remove(at: index)
}
}
}
var testArray: Array<Int> = [1, 2]
let toBeRemoved: Int = 1
testArray.remove(object: toBeRemoved)
testArray
Results in
[2]
How to remove single object in array from multiple matching object
Swift 2
Solution when using a simple Swift array:
var myArray = [1, 2, 2, 3, 4, 3]
if let index = myArray.indexOf(2) {
myArray.removeAtIndex(index)
}
It works because .indexOf
only returns the first occurence of the found object, as an Optional (it will be nil
if object not found).
It works a bit differently if you're using NSMutableArray:
let nsarr = NSMutableArray(array: [1, 2, 2, 3, 4, 3])
let index = nsarr.indexOfObject(2)
if index < Int.max {
nsarr.removeObjectAtIndex(index)
}
Here .indexOfObject
will return Int.max
when failing to find an object at this index, so we check for this specific error before removing the object.
Swift 3
The syntax has changed but the idea is the same.
Array:
var myArray = [1, 2, 2, 3, 4, 3]
if let index = myArray.index(of: 2) {
myArray.remove(at: index)
}
myArray // [1, 2, 3, 4, 3]
NSMutableArray:
let myArray = NSMutableArray(array: [1, 2, 2, 3, 4, 3])
let index = myArray.index(of: 2)
if index < Int.max {
myArray.removeObject(at: index)
}
myArray // [1, 2, 3, 4, 3]
In Swift 3 we call index(of:)
on both Array and NSMutableArray, but they still behave differently for different collection types, like indexOf
and indexOfObject
did in Swift 2.
Swift: Better way to remove a specific Object from an array?
Use firstIndex(where:)
(previously called index(where:)
in Swift 4.1 and earlier) to search the array for your object using the predicate { $0 === objectToRemove }
, then call remove(at:)
on the array to remove it:
if let idx = objectArray.firstIndex(where: { $0 === objectToRemove }) {
objectArray.remove(at: idx)
}
This allows you to search for your object whether it is Equatable
or not.
Swift: Remove element from array quickly like in Lua
I think the filter
is the way to go for you. You could also remove the element by index
but I would still go with the filter
method:
Filter:
array = array.filter() { $0 !== value }
Remove by index:
if let index = array.index(where: { $0 == value }) {
array.remove(at: index)
}
Related Topics
Download Array of Images as Byte Array and Convert to Images
Cell Size Not Updating After Changing Flow Layout'S Itemsize
How to Debug 'Unrecognized Selector Sent to Instance' Error
Hide Strange Unwanted Xcode Logs
How to Adjust the Anchor Point of a Calayer, When Auto Layout Is Being Used
How to Create a Basic Uibutton Programmatically
Autoresizing Masks Programmatically VS Interface Builder/Xib/Nib
How to Create a Multiline Uitextfield
Check If My App Has a New Version on Appstore
How to Center Horizontally Uicollectionview Cells
Create Tap-Able "Links" in the Nsattributedstring of a Uilabel
How to Store Custom Objects in Nsuserdefaults
Create Singleton Using Gcd'S Dispatch_Once in Objective-C
How to Intercept Touches Events on a Mkmapview or Uiwebview Objects