SIDHARTH P U
SIDHARTH P U

Reputation: 292

Difference between reverse() and reversed() in swift

Code1:

let word = "Backwards"
for char in word.reversed() {
    print(char, terminator: "")
}

Code 2:

var characters: [Character] = ["C", "a", "f", "é"]
characters.reverse()
print(characters)

What is the difference between these two codes?

Upvotes: 0

Views: 1468

Answers (4)

SPatel
SPatel

Reputation: 4956

reversed()

return completely new array with reversed order of original

reverse()

reverse collection it self.

Upvotes: 3

Aamir
Aamir

Reputation: 17007

I think an important missing aspect of reverse and reversed are their time complexities.

Apart from the fact that reverse is mutating function defined over a collection and reversed returns a new object altogether, the time complexity of reverse is O(n) and reversed is O(1).

O(1) time complexity seems surprising but if we look at the return type of reversed call it returns ReversedCollection object which internally points to the original collection unless original contents are modified. So basically it is just presenting/accessing the elements of the base collection in reversed manner to save time and memory.

Following example shows that reversed array remains same as the original array unless it is modified:

var originalArray = [1, 2, 3]
var reversedArray = originalArray.reversed()

print("0th index of OriginalArray \(originalArray[0])")
print("0th index of ReversedBaseArray \(reversedArray._base[0])")


print("0th index of OriginalArray \(originalArray.first)")
print("0th index of ReversedBaseArray \(reversedArray.first)")

originalArray[0] = 4 // Modification makes a separate copy of each instance
print("0th index of OriginalArray \(originalArray[1])")
print("0th index of ReversedBaseArray \(reversedArray._base[1])")


// Console Output:
// 0th index of OriginalArray 1
// 0th index of ReversedBaseArray 1


// First element of OriginalArray Optional(1)
// First element of ReversedBaseArray Optional(3)


// 0th index of OriginalArray 4
// 0th index of ReversedBaseArray 1

Upvotes: 1

matt
matt

Reputation: 535850

You yourself exposed the difference perfectly. All you have to do is look at your own code.

  • characters.reverse() changes the value of characters.

  • But word.reversed() leaves word unchanged.

Upvotes: 2

Karthik Kumar
Karthik Kumar

Reputation: 1385

Below are the differences

Code1: create an iterator to traverse in reverse order

let word = "Backwards" 
    for char in word.reversed() {
        print(char, terminator: "") 
}

Code 2: reverse the content

var characters: [Character] = ["C", "a", "f", "é"]
characters.reverse()
print(characters)

Upvotes: 1

Related Questions