@@ -7,6 +7,7 @@ Types and operations for working with complex numbers.
7
7
The ` Complex ` type is generic over an associated ` RealType ` ; complex numbers
8
8
are represented as two ` RealType ` values, the real and imaginary parts of the
9
9
number.
10
+
10
11
```
11
12
let z = Complex<Double>(1, 2)
12
13
let re = z.real
@@ -32,32 +33,42 @@ map them into Swift types by converting pointers.
32
33
Because the real numbers are a subset of the complex numbers, many
33
34
languages support arithmetic with mixed real and complex operands.
34
35
For example, C allows the following:
36
+
35
37
``` c
36
38
#include < complex.h>
37
39
double r = 1 ;
38
40
double complex z = CMPLX(0 , 2 ); // 2i
39
41
double complex w = r + z; // 1 + 2i
40
42
```
41
- The ` Complex ` type does not provide such mixed operators. There are two
42
- reasons for this choice. First, Swift generally avoids mixed-type
43
- arithmetic, period. Second, mixed-type arithmetic operators lead to
44
- undesirable behavior in common expressions when combined with literal
45
- type inference. Consider the following example:
43
+
44
+ The ` Complex ` type does not provide such mixed operators:
45
+
46
46
``` swift
47
- let a: Double = 1
48
- let b = 2 * a
47
+ let r = 1.0
48
+ let z = Complex (imaginary : 2.0 )
49
+ let w = r + z // error: binary operator '+' cannot be applied to operands of type 'Double' and 'Complex<Double>'
49
50
```
50
- If we had a heterogeneous ` * ` operator defined, then if there's no prevailing
51
- type context (i.e. we aren't in an extension on some type), the expression
52
- ` 2*a ` is ambiguous; ` 2 ` could be either a ` Double ` or ` Complex<Double> ` . In
53
- a ` Complex ` context, the situation is even worse: ` 2*a ` is inferred to have
54
- type ` Complex ` .
55
-
56
- Therefore, the ` Complex ` type does not have these operators. In order to write
57
- the example from C above, you would use an explicit conversion:
51
+
52
+ In order to write the example from C above in Swift, you have to perform an
53
+ explicit conversion:
54
+
58
55
``` swift
59
- import ComplexModule
60
56
let r = 1.0
61
- let z = Complex< Double > (0 , 2 )
62
- let w = Complex (r) + z
57
+ let z = Complex (imaginary : 2.0 )
58
+ let w = Complex (r) + z // OK
59
+ ```
60
+
61
+ There are two reasons for this choice. Most importantly, Swift generally avoids
62
+ mixed-type arithmetic. Second, if we _ did_ provide such heterogeneous operators,
63
+ it would lead to undesirable behavior in common expressions when combined with
64
+ literal type inference. Consider the following example:
65
+
66
+ ``` swift
67
+ let a: Double = 1
68
+ let b = 2 * a
63
69
```
70
+
71
+ ` b ` ought to have type ` Double ` , but if we did have a Complex-by-Real ` * `
72
+ operation, ` 2*a ` would either be ambiguous (if there were no type context),
73
+ or be inferred to have type ` Complex<Double> ` (if the expression appeared
74
+ in the context of an extension defined on ` Compex ` ).
0 commit comments