Home > Software engineering >  How to remove numbers with 5 from an array Swift?
How to remove numbers with 5 from an array Swift?

Time:08-09

Could you please tell me how to remove numbers with 5 in them from an array?

let array = [5, 3, 20, 15, 12, 88, 105, 45, 1055, 555]

CodePudding user response:

As Matt mentioned in the comments the question isn't clear...

Either way, my first thought would be you using filter which is for the use case. So perhaps you want to use something like this:

    let array = [5, 3, 20, 15, 12, 88, 105, 45, 1055, 555]
    let filtered = array.filter { number in
      return !String(number).contains("5")
    }
    print(filtered)

Assuming you want an array of Ints... mapping to a string array before filter would be another approach.

CodePudding user response:

Alternative way:- Here you don't need to assign value to another variable after deleting elements, Which will save your memory.

var array = [5, 3, 20, 15, 12, 88, 105, 45, 1055, 555]
           array.removeAll { obj in
                if obj % 5 != 0  {
                    return false
                }
                return ((obj/5) % 2) != 0
            }

print(array) //[3, 20, 12, 88]
  • Related