Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 自动拥有+;=定义+;时定义;?_Swift_Swift3 - Fatal编程技术网

Swift 自动拥有+;=定义+;时定义;?

Swift 自动拥有+;=定义+;时定义;?,swift,swift3,Swift,Swift3,我有一个类型,它定义了一个自定义的+。我想知道Swift是否可以自动为+=编写定义,即a+=b-->a=a+b。理想情况下,我不必为我编写的每个运算符编写相应的赋值运算符 示例代码: class A { var value: Int init(_ value: Int) { self.value = value } static func +(lhs: A, rhs: A) -> A { return A(lhs.valu

我有一个类型,它定义了一个自定义的
+
。我想知道Swift是否可以自动为
+=
编写定义,即
a+=b
-->
a=a+b
。理想情况下,我不必为我编写的每个运算符编写相应的赋值运算符

示例代码:

class A {
    var value: Int

    init(_ value: Int) {
        self.value = value
    }

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

var a = A(42)
let b = A(10)

// OK
let c = a + b

// error: binary operator '+=' cannot be applied to two 'A' operands
// Ideally, this would work out of the box by turning it into a = a+b
a += b

通常在定义
+
时必须定义
+=

您可以创建一个声明
+
+=
Summable
协议,但仍然需要定义
+
函数,因为添加任意类型没有具体意义。下面是一个例子:

protocol Summable {
    static func +(lhs: Self, rhs: Self) -> Self
    static func +=(lhs: inout Self, rhs: Self)
}

extension Summable {
    static func +=(lhs: inout Self, rhs: Self) { lhs = lhs + rhs }
}

struct S: Summable { }

func +(lhs: S, rhs: S) -> S {
    // return whatever it means to add a type of S to S
    return S()
}

func f() {
    let s0 = S()
    let s1 = S()
    let _ = s0 + s1

    var s3 = S()

    s3 += S()  // you get this "for free" because S is Summable
}

你能发布重载运算符方法的代码吗?@ZeMoon我添加了示例代码谢谢。Swift没有自动执行此操作有什么原因吗?对于简单类型,例如
Int
+=
,定义良好。当您有一个更复杂的自定义类型时,修改
+=
等式的左侧可能会产生您不想要的副作用。为了简单和/或安全起见,每次使用
+
构造一个新对象可能是唯一正确的做法。因此,从Swift的角度来看,明确声明
+=
是正确的要求。当你使用
Summable
时,你是在说你理解(并且同意)了
+=
的副作用。我认为写
+=
意味着你可以执行加法。我假设它是语法上的糖分,而不是语言的真正组成部分。记住,
+=
改变了它的一个参数。有许多复杂类型的突变要么是完全不允许的,要么是突变必须遵循一条非常明确的路径。在这些类型的对象中,
+
运算符可能有意义,但
+=
将被禁止。由于Swift无法先验地知道任意自定义类型的需求可能是什么,因此它不能假设在自定义
+
可用时自动生成
+=
是有效的。所以不,这不是语法上的糖
+=
本身就是一个成熟的运营商。啊,谢谢。忘记了
+=
可以任意更改
lhs
。尽管如此,我还是希望有某种方式选择“普通”行为,即
a+=b
=
a=a+b