不能使用在函数内定义的struct的重载运算符

时间:2018-01-11 11:56:23

标签: swift operator-overloading

我在函数内部定义了一个结构,并希望在该结构上定义和使用重载运算符:

func test() {
    struct Foo {
        let value: Int

        static func +(left: Foo, right: Foo) -> Foo {
            return Foo(value: left.value + right.value)
        }
    }

    print(Foo(value: 2) + Foo(value: 3))
}

但这不起作用,我收到以下错误:

test.swift:10:25: error: binary operator '+' cannot be applied to two 'Foo' operands
    print(Foo(value: 2) + Foo(value: 3))
          ~~~~~~~~~~~~~ ^ ~~~~~~~~~~~~~
test.swift:10:25: note: overloads for '+' exist with these partially matching parameter lists: (Float, Float), (Double, Double), (Float80, Float80), (UInt8, UInt8), (Int8, Int8), (UInt16, UInt16), (Int16, Int16), (UInt32, UInt32), (Int32, Int32), (UInt64, UInt64), (Int64, Int64), (UInt, UInt), (Int, Int), (String, String), (C, S), (S, C), (RRC1, RRC2), (Self, Self.Stride), (Self.Stride, Self), (UnsafeMutablePointer<Pointee>, Int), (Int, UnsafeMutablePointer<Pointee>), (UnsafePointer<Pointee>, Int), (Int, UnsafePointer<Pointee>)
    print(Foo(value: 2) + Foo(value: 3))
                        ^

在非全局结构上定义运算符还是我遗漏了某些东西?是否有任何选项可以在不将结构移动到文件范围的情况下完成此工作?

1 个答案:

答案 0 :(得分:0)

您不能声明带有重载的结构,然后在同一个函数中使用它。在编译时,过载将不知道。 所以你必须把结构放在函数之外,就像这样

struct Foo{
    let value: Int


    static func +(lhs: Foo, rhs: Foo) -> Foo {
        return Foo(value: lhs.value + rhs.value)
    }
}

func test() {

    print(Foo(value: 2) + Foo(value: 3))
}