基本 == 重载失败

Basic == overloading fails

我想要的最终结果是能够与 [Server] 个对象比较是否相等,如下所示:

let server1 = Server(username: "1")
let server2 = Server(username: "2")

let server1Array = [server1]
let server2Array = [server2]

print(server1Array == server2Array)

我有一个名为 Server 的 class,我想为 Server 数组 重载 ==

// Server.swift

import Foundation
infix operator ==: AssignmentPrecedence

class Server: ServerRepresentable {
    let username: String

    init(username: String) {
        self.username = username
    }
}

// This protocol's only purpose is to allow me to use the `where` clause in the extension below 
protocol ServerRepresentable {
    var username: String { get }
}

extension Array where Element: ServerRepresentable {
    static func == (lhs: Array<ServerRepresentable>, rhs: Array<ServerRepresentable>) {
        let server1Usernames = lhs.map { [=11=].username }
        let server2Usernames = rhs.map { [=11=].username }

        // ERROR: Cannot convert value of type '[String]' to expected argument type 'Bool'
        return server1Usernames == server2Usernames
    }
}

如您所见,当我尝试执行server1Usernames == server2Usernames,都是字符串数组。这很奇怪,因为 == 运算符应该已经在 [String] 比较中超载了。

什么给了?编译器是否因为我在此 class 中重载运算符而感到困惑?

无需扩展 Array。只需确保您的 Server 符合 Equatable 协议:

class Server: ServerRepresentable, Equatable {
    let username: String
    init(username: String) {
        self.username = username
    }
    static func == (lhs: Server, rhs: Server) -> Bool {
        lhs.username == rhs.username
    }
}

let server1 = Server(username: "1")
let server2 = Server(username: "2")

let server1Array = [server1]
let server2Array = [server2]

print(server1Array == server2Array)  // "false\n"

关于您的问题,您忘记添加 returning 类型 Bool 但是您发布的代码显示的错误应该是 Unexpected non-void return 无效函数中的值

这仅适用于字符串、整数、双精度、浮点数组。

你可以试试这样的

检查是否有差异

            for server1 in servers1 {
                        var name1 = [String]()
                        var name2 = String()
                        
                        for server2 in servers2 {name1.append(server2.name)}
                        
                        name2 = server1.name
                        
                        if name1.contains(name2) {
                            print("found duplication")
                         
                        }

找出不同点


for server1 in servers1 {
                        var name1 = [String]()
                        var name2 = String()
                        
                        for server2 in servers2 {name1.append(server2.name)}
                        
                        name2 = server1.name
                        
                            print(name1. difference(name2))
}
// 
extension Array where Element: Hashable {
    func difference(from other: [Element]) -> [Element] {
        let thisSet = Set(self)
        let otherSet = Set(other)
        return Array(thisSet.symmetricDifference(otherSet))
    }
}