Skip to content

Instantly share code, notes, and snippets.

@allenu
Last active October 28, 2017 17:28
Show Gist options
  • Save allenu/2098877d7575b3dde22f67ec1cfbb859 to your computer and use it in GitHub Desktop.
Save allenu/2098877d7575b3dde22f67ec1cfbb859 to your computer and use it in GitHub Desktop.
Compiler error when comparing two arrays of structs in Swift
//
// CompareTest.swift
//
// Created by Allen Ussher on 10/28/17.
// Copyright © 2017 Ussher Press. All rights reserved.
//
import Foundation
struct StructWithValue {
let value: Int
init(value: Int) {
self.value = value
}
}
func ==(lhs: StructWithValue, rhs: StructWithValue) -> Bool {
return lhs.value == rhs.value
}
struct StructWithArray {
let array: [StructWithValue]
init(array: [StructWithValue]) {
self.array = array
}
}
func ==(lhs: StructWithArray, rhs: StructWithArray) -> Bool {
// Compiler error here: Binary operator '==' cannot be applied to two '[StructWithValue]' operands
return lhs.array == rhs.array
}
// Well, it works if you make the structs Equatable. Silly me.
import Foundation
struct StructWithValue: Equatable {
let value: Int
init(value: Int) {
self.value = value
}
static func ==(lhs: StructWithValue, rhs: StructWithValue) -> Bool {
return lhs.value == rhs.value
}
}
struct StructWithArray: Equatable {
let array: [StructWithValue]
init(array: [StructWithValue]) {
self.array = array
}
static func ==(lhs: StructWithArray, rhs: StructWithArray) -> Bool {
// Compiler error here: Binary operator '==' cannot be applied to two '[StructWithValue]' operands
return lhs.array == rhs.array
}
}
@allenu
Copy link
Author

allenu commented Oct 28, 2017

The compiler error on line 32 of CompareTest.swift makes me sad. :(

But if you make them Equatable, it works fine. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment