UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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)
print(musicians)

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))     
        print(name)

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

2      

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.

2      

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

print(array)

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

2      

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

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.