Removing object from array in Swift 3

前端 未结 13 2046
余生分开走
余生分开走 2020-12-08 12:49

In my application I added one object in array when select cell and unselect and remove object when re-select cell. I used that code but give me error.

extens         


        
相关标签:
13条回答
  • 2020-12-08 13:12

    In Swift 3 and 4

    var array = ["a", "b", "c", "d", "e", "f"]
    
    for (index, element) in array.enumerated().reversed() {
        array.remove(at: index)
    }
    

    From Swift 4.2 you can use more advanced approach(faster and memory efficient)

    array.removeAll(where: { $0 == "c" })
    

    instead of

    array = array.filter { !$0.hasPrefix("c") }
    

    Read more here

    0 讨论(0)
  • 2020-12-08 13:12

    This is official answer to find index of specific object, then you can easily remove any object using that index :

    var students = ["Ben", "Ivy", "Jordell", "Maxime"]
    if let i = students.firstIndex(of: "Maxime") {
         // students[i] = "Max"
         students.remove(at: i)
    }
    print(students)
    // Prints ["Ben", "Ivy", "Jordell"]
    

    Here is the link: https://developer.apple.com/documentation/swift/array/2994720-firstindex

    0 讨论(0)
  • 2020-12-08 13:16

    The correct and working one-line solution for deleting a unique object (named "objectToRemove") from an array of these objects (named "array") in Swift 3 is:

    if let index = array.enumerated().filter( { $0.element === objectToRemove }).map({ $0.offset }).first {
       array.remove(at: index)
    }
    
    0 讨论(0)
  • 2020-12-08 13:17

    Swift 4

    var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
    
    if let index = students.firstIndex(where: { $0.hasPrefix("A") }) {
       students.remove(at: index)
    }
    
    0 讨论(0)
  • 2020-12-08 13:24
    1. for var index = self.indexOfObject(object); index != NSNotFound; index = self.indexOfObject(object) is for loop in C-style and has been removed

    2. Change your code to something like this to remove all similar object if it have looped:

      let indexes = arrContacts.enumerated().filter { $0.element == contacts[indexPath.row] }.map{ $0.offset }
      for index in indexes.reversed() {
         arrContacts.remove(at: index)
      }
      
    0 讨论(0)
  • 2020-12-08 13:26
    var a = ["one", "two", "three", "four", "five"]
    
    // Remove/filter item with value 'three'
    a = a.filter { $0 != "three" }
    
    0 讨论(0)
提交回复
热议问题