WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

removing from an array inside a function

Forums > Swift

Good mrng all.

i can write the code to remove from where i just have the variable....

var musicians = ["Neil Young", "Kendrick Lamar", "Flo Rida", "Fetty Wap"]
musicians.remove(at: 1)

but i'm failing when i try to remove inside a function. Appreciate any help you can give....thanks

func Elements1(array: [Int]) -> Int {
    for name in array {
        remove(name(at: 2))     

    return 0
Elements1(array:[1, 2, 3, 4, 5])


The remove function is part of the Array struct. Your first example works because you call remove on the musicians array. Your second example causes a compiler error because you are calling remove on an integer.

To remove elements from an array that you pass as a function argument, you must make the argument an inout argument so you can make changes to the array. By default arrays passed as arguments to functions are immutable. Put the inout text before the data type of the argument.

func Elements1(array: inout[Int]) -> Int

What are you trying to do in the second example? Looking at the code, it goes through each element in the array and removes the third element. Eventually the code will crash because you'll try to remove the third element when the array has fewer than three elements.


Not sure what the function is for. For start the function will always return 0 regardless of the array. Think you might want something like this

func Elements1(array: inout[Int]) -> [Int] {
    array.remove(at: 2)
    return array

var array = [1, 2, 3, 4, 5]

Elements1(array: &array) //<- note you have to use & and the array has to be a var


Note if you run this more Elements1 more then four times it will crash


thanks guys. much appreciate the replies. will review your thoughts as it relates to my initial code, and rewrite, given both your insights.


Hacking with Swift is sponsored by Emerge

SPONSORED Optimize your app’s startup time, binary size, and overall performance using Emerge’s advanced app optimization and monitoring tools. Reliably measure app size, speed up your app's startup time with Emerge's Launch Booster, and much more. Emerge is actively used by many of the top mobile development teams in the world.

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.