Overriding func +( [ Double ], [ Double ] )
Clash Royale CLAN TAG#URR8PPP
Overriding func +( [ Double ], [ Double ] )
I want to define + function
of [ Double ]
like below.
+ function
[ Double ]
[ 2.0, 3.0, 4.0 ] + [ 5.0, 6.0, 7.0 ] -> [ 7.0, 9.0, 11.0 ]
So, I defined + function
like below.
+ function
func +( _ l: [ Double ], _ r: [ Double ] ) -> [ Double ]
guard l.count == r.count else fatalError()
var v = [ Double ]( repeating: 0, count: l.count )
// Some adding operation
return v
It works unless without Foundation framework.
But when I include Foundation framework, it seems that in Foundation framework +( Array, Array )
has been already defined. So,
+( Array, Array )
[ 2.0, 3.0, 4.0 ] + [ 5.0, 6.0, 7.0 ]
gets
[ 2.0, 3.0, 4.0, 5.0, 6.0, 7.0 ]
Does anyone know how to avoid this? Or is overriding +([ Double ],[ Double ])
alongside Foundation framework
impossible?
+([ Double ],[ Double ])
Foundation framework
override
Is there an option to use
++
as an operator?– Eimantas
Aug 6 at 16:15
++
@RakeshaShastri Thanks, but adding override keyword makes error.
'override' can only be specified on class members
– Satachito
Aug 6 at 16:19
'override' can only be specified on class members
@Satachito the
+
operator for Double
(and any type of array) is used for concatenation (including String
type too). So you're out of luck unless you want to swim against quite matured convention.– Eimantas
Aug 6 at 16:28
+
Double
String
Just tried the operator, and the override works, provided the override is declared before performing the operation.
– Cristik
Aug 7 at 15:51
1 Answer
1
As +
for two Array
operands has already been reserved for concatenating arrays, you'd have to resort to declaring your own infix
operator. E.g. ~+
:
+
Array
infix
~+
import Accelerate
infix operator ~+
func ~+( _ l: [ Double ], _ r: [ Double ] ) -> [ Double ]
guard l.count == r.count else fatalError()
var v = [ Double ]( repeating: 0, count: l.count )
vDSP_vaddD( l, 1, r, 1, &v, 1, vDSP_Length( v.count ) )
return v
print([ 2.0, 3.0, 4.0 ] ~+ [ 5.0, 6.0, 7.0 ]) // [7.0, 9.0, 11.0]
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Did you try adding the
override
keyword?– Rakesha Shastri
Aug 6 at 16:15