如何为Swift中的私有枚举编写相等方法

7

我是Swift的新手,试图编写一个符合Equatable协议的私有枚举。以下是我代码的简化版本:

class Baz {

    /* Other members in class Baz */

    private enum Test: Equatable {
        case Foo
        case Bar
    }

    private func == (lhs: Test, rhs: Test) -> Bool {
        //comparison
    }
}

在“==”方法的行上,编译器抱怨“仅允许在全局范围内使用运算符”。当我将enum Test和“==”方法更改为public,然后将“==”移出类时,错误消失了。
我的问题是如何正确实现私有枚举的“==”方法?
感谢所有帮助我的人。我没有指定我的私有枚举和上面的函数在一个类中..(代码已更新)

2
我看到有两个答案得出你的代码是正确的,他们显然假设你在全局范围内实现了这个代码,而我从你的错误信息中推断出你试图在另一个类型的定义内部(例如一个class)实现这个代码。也许你可以澄清一下。 - Rob
3个回答

3

虽然这对您可能没有立即用处,但值得注意的是,在Swift 3中,从beta 5开始,您可以将其作为类型内的static func。请参见Xcode 8 Beta Release Notes

Operators can be defined within types or extensions thereof. For example:

 struct Foo: Equatable {
     let value: Int
     static func ==(lhs: Foo, rhs: Foo) -> Bool {
         return lhs.value == rhs.value
     }
 }

Such operators must be declared as static (or, within a class, class final), and have the same signature as their global counterparts.

这也适用于枚举类型。因此:

这适用于enum类型,也是如此。

private enum Test: Equatable {
    case foo
    case bar

    static func ==(lhs: Test, rhs: Test) -> Bool {
        // your test here
    }
}

甚至当这个Test被实现在另一个类型中时,它也能正常工作。


2

我在Playground中尝试了一下,它对我有效:

private enum Test: Equatable {
    case Foo
    case Bar
}

private func ==(lhs: Test, rhs: Test) -> Bool {
    return true
}

class A {
    func aFunc() {
        let test: Test = .Foo
        let test2: Test = .Foo

        if (test == test2) {
            print("Hello world")
        }
    }
}

let a = A()

a.aFunc() // Hello world

您能编辑您的问题并附上代码吗?这样我才能根据您的问题进行修改。


你肯定不希望发生这种情况:http://swiftlang.ng.bluemix.net/#/repl/57acfee6f01121f27706b037 - Alexander

1

你所做的一切都没有问题:

private enum Test: Equatable {
    case Foo
    case Bar
}

private func ==(lhs: Test, rhs: Test) -> Bool {
    // Put logic here
}

private let test = Test.Foo
private let test2 = Test.Foo

if (test == test2) {
    print("Hello world")
}

请参阅此文章以获取详细信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接