Trikalabs
  • Home
  • Best online TDD videos
  • Book Suggestions
  • About Me
  • Contact
Trikalabs
No Result
View All Result

Equal arrays

by fragi
May 24, 2023
in Uncategorized
Share on FacebookShare on Twitter

In this short article we explore when two array are equal in Swift.

Let’s start we the obvious cases:

Swift
1
2
3
4
let a = [1, 2, 3]
let b = [1, 2, 3]
 
a == b

a == b is true as expected.

Let’s now test the following case

Swift
1
2
3
4
let a = [1, 2, 3]
let b = [1, 3, 2]
 
a == b

a == b is false.

In order two array to be equal they have to have the same elements in the same order.

Let’s see what happens when we have classes.

Swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class A: Equatable {
    static func == (lhs: A, rhs: A) -> Bool {
        lhs.i == rhs.i
    }
    
    let i: Int
    
    init(i: Int) {
        self.i = i
    }
}
 
let a = [A(i: 1), A(i: 2)]
let b = [A(i: 1), A(i: 2)]
let c = a
let d = [A(i: 2), A(i: 1)]
 
a == b
a == c
b == c
a == d

a == b,  a == c and b == c are true.

The same logic applies. In order to be equal each element on the same position has to be equal.

fragi

fragi

Related Posts

Uncategorized

C Union equivalent in Swift

May 24, 2023

In C we can declare unions as follows: So the same storage is used for the int and uint....

Uncategorized

Unit tests in playground

May 24, 2023

In this short article we will run unit tests on a Playground. Lets create a Playground and add the code...

Next Post

C Union equivalent in Swift

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Advertise
  • Privacy & Policy
  • Contact

© 2019 Trikalabs Ltd. All rights reserved.

No Result
View All Result
  • Home
  • About Me
  • A curated list with the best free online TDD videos
  • Book Suggestions
  • Pinner Code Club

© 2019 Trikalabs Ltd. All rights reserved.

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.