You are getting an error because you are taking the sum of objects
with object
and there is no function for this operation.
To use any operator (+=
is an operator) you need to declare functions for it. These are global functions. Which means they are not put inside the Type they work on. Under it is fine.
This is just a Type with some properties.
class MyType {
var myInt : Int = 0
var myString : String = ""
var myFloat : Float = 0
init(int: Int, string: String, float: Float) {
myInt = int
myString = string
myFloat = float
}
}
These are functions for the operators.
The first one is just a +
, it returns a new instance of MyType
Notice how you need to combine all properties for which this makes sense.
As an example I did not take the sum of myFloat
, only the other properties.
func +(lhs:MyType,rhs:MyType) -> MyType {
let intSum = lhs.myInt + rhs.myInt
let stringSum = lhs.myString + rhs.myString
return MyType(int: intSum, string: stringSum,float: lhs.myFloat)
}
The second one uses inout
to alter the left hand side instance (lhs). There is no return
in this function. Since the left hand side instance is updated.
func +=(inout lhs:MyType, rhs:MyType) {
lhs.myInt += rhs.myInt
lhs.myString += rhs.myString
}
Notice how these functions expect two parameters of the same Type. If objects
and object
are not of the same type (I am guessing one might be and Array
or Dictionairy
) then you need to create a function to take the sum of two unrelated Types.
This is another Type
class MyOtherType {
var myDouble : Double = 0
}
This function uses the operator to take the sum of two otherwise unrelated Types
func +(lhs:MyType,rhs:MyOtherType) -> MyType {
let floatSum = lhs.myFloat + Float(rhs.myDouble)
return MyType(int: lhs.myInt, string: lhs.myString, float: floatSum)
}
Some tests
If you do not write the operator function you will get this:
let alpha = MyType(int: 20, string: "hello ", float: 0.5)
let beta = MyType(int: 22, string: "world", float: 0.75)
let delta = alpha + beta // error: binary operator '+' cannot be applied to two 'MyType' operands
If you do:
let alpha = MyType(int: 20, string: "hello ", float: 0.5)
let beta = MyType(int: 22, string: "world", float: 0.75)
let delta = alpha + beta // 42, "hello world", 0.5
If you do not write the operator function to take the sum with MyOtherType
:
let alpha = MyType(int: 20, string: "hello ", float: 0.5)
let beta = MyOtherType()
let delta = alpha + beta // error: binary operator '+' cannot be applied to operands of type 'MyType' and 'MyOtherType'
It is important to include both the Type and declaration of objects
and object
in your question. Also, always copy the full error message, which should like something like this:
error: binary operator '+' cannot be applied to operands of type 'MyType' and 'MyOtherType'
If objects
is an Array
your sum function would look like this :
func +=<T where T : _ArrayType>(inout lhs:T, rhs:T.Generator.Element) {
lhs.append(rhs)
}