Home > Mobile >  remove an index number from array
remove an index number from array

Time:10-11

I have this code and the task is to write a function that remove the same index number in the function parameter

func deleteElementInArray(arr: [Int], index: Int) -> [Int] {

    var inde = index
    var array = arra[inde]
    var result = array.remove(at: inde) // I got error here Value of type 'Int' has 
                                           //no member 'remove'
    return result

}

sample output

arr [-3 , 4 , 0]

index 0

output [4 , 0]

CodePudding user response:

You are calling the remove function on the Int value at the given index, not on the array:

func deleteElementInArray(arr: [Int], index: Int) -> [Int] {
    // make a mutable copy of the array
    var array = arr
    // remove the item at given index
    array.remove(at: index)
    // return the array  
    return array
}

CodePudding user response:

    var array = arra[inde]
    var result = array.remove(at: inde) // I got error here Value of type 'Int' has 

The compiler has described the problem. Int is a standard data type. array is assigned to Int - which has no member called remove. You are probably trying to define

var array:[Int] = [2, 3, 5, 7, 11, 13, 17]
 
array.remove(at: 3)

You are trying to do - array=arra

Note the difference between an array of Int, and an Int.

CodePudding user response:

As others have stated, you wrote your code to try to remove an item from an Integer that you extracted from your array.

You can use the same name for a local var that you use for the input parameter. That works because the new variable is defined at a different scope. Adding an error check so you don't crash if you call it with a bad array index, your function could be rewritten like this:

func deleteElementInArray(array: [Int], index: Int) -> [Int] {
    var array = array
    if array.indices.contains(index) {
        array.remove(at: index)
    }
    return array
}

Note that the Array function remove(at:) already does what you want (excluding the error checking). Ok, `remove(at:) modifies the array in place, where your function creates a mutable copy and modifies that.)

  • Related