GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

What's the difference between this two examples.

Forums > Swift

I've been looking at Extensions and I am seeing strange behavior between these two pieces of code, which I assumed were equivalent.

1st code

extension Array where Element: Equatable {
    mutating func removing(_ obj: Element) -> Self {
        filter { $0 != obj }
    }
}

var numbersBase = [1, 42, 2, 42, 3, 42]
print(numbersBase.removing(42))

this returns the expected value of [1, 2, 3]

However if I rewrite it to

extension Array where Element: Equatable {
    mutating func removing(_ obj: Element) {
        self = filter { $0 != obj }
    }
}

var numbersBase = [1, 42, 2, 42, 3, 42]
print(numbersBase.removing(42))

it returns the value () Why are these not equivalent?

   

You don't return a value in your second example so what gets printed is just (), which is the Void type, which is technically what is returned by functions with no return value.

Whereas in your first example, print spits out whatever value you return, since removing gives back a value of type Self.

   

To some extent, they are equivalent, but getting at the result is different in each case.

In the first example, removing() returns a new Array: [1, 2, 3]. The original Array has not been altered. If you want to use the new array somewhere in your program, you would have to capture it in a new variable.

Calling print(numbersBase) will still output [1, 42, 2, 42, 3, 42].

In the second example, you have altered numbersBase in-place. Although the function itself returns (), numbersBase has changed.

Now, when you call print(numbersBase), you get [1, 2, 3].

The original version of numbersBase no longer exists.

   

Hacking with Swift is sponsored by Alex.

SPONSORED Alex is the iOS & Mac developer’s ultimate AI assistant. It integrates with Xcode, offering a best-in-class Swift coding agent. Generate modern SwiftUI from images. Fast-apply suggestions from Claude 3.5 Sonnet, o3-mini, and DeepSeek R1. Autofix Swift 6 errors and warnings. And so much more. Start your 7-day free trial today!

Try for free!

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.