|
Maps复合类型 map<K, V> 用于将 K 类型的键与 V 类型的相应值关联起来例如,map<Int, Int> 使用 Int 类型作为其键和值:4 x5 b9 h4 L* o6 \% m
- struct IntToInt {
9 H7 w6 d# h* }4 }' R, n& Y& Z - counters: map<Int, Int>;
0 h( ? F, P P8 C- E6 w" f - }
复制代码
* ?4 u9 w: O3 ]& y% D. ]" l: t. {- N
6 h# l" }) s" K* K
操作
2 B, c5 W- ~ B) d0 K) N& W1 T) ^Declare, emptyMap()
: l( p9 U" `+ W( M. N作为局部变量,使用标准库的 emptyMap() 函数:
' D& a/ a# ], z* m! j- let fizz: map<Int, Int> = emptyMap();
" p" f. T7 b- c$ Z7 S - let fizz: map<Int, Int> = null; // identical to the previous line, but less descriptive
复制代码 作为 持久状态变量:: ~, L# ^+ G; I
- contract Example {$ _6 _4 n! B( |# _4 q6 n
- fizz: map<Int, Int>; // Int keys to Int values
, [3 t$ m7 n: O1 O9 j8 R - init() {
. `6 S/ N6 D7 E% u! v - self.fizz = emptyMap(); // redundant and can be removed!
' q. _4 z" ?& P2 `& w/ \ - }: L: a' j. d0 v
- }
复制代码 请注意,类型为 map<K, V> 的 持久状态变量 默认为空,不需要默认值,也不需要在 init() 函数中进行初始化。
- G; j8 }4 F! n
, F6 Z* y2 ^* B7 G3 K2 i, G. u# a9 e( E
! r0 v' i" a1 _# s" o
设置值,.set()! R7 O# n5 x3 E* N/ P% _
要设置或替换键下的值,请调用 .set() 方法,所有 map 都可以使用该方法。
8 h) h1 s& ?! L$ L- // Empty map7 h/ H5 u" p, `4 U/ Z
- let fizz: map<Int, Int> = emptyMap();
0 w8 i3 D" f6 z6 K6 a
( V5 i) h L' }2 f9 M8 P, c, u, i, m- // Setting a couple of values under different keys
& w [; |, W1 y5 m: l: P - fizz.set(7, 7);% M$ ]$ X, V5 Y* D) W# J) a
- fizz.set(42, 42);4 Q$ B2 N: w+ f9 m
- * c1 z6 N% c! O h1 `6 ?
- // Overriding one of the existing key-value pairs
1 e/ T3 I8 F+ r' l1 B% L0 ~ - fizz.set(7, 68); // key 7 now points to value 68
复制代码- // Empty map8 D2 O4 a/ Y, Z C3 B5 B K
- let fizz: map<Int, Int> = emptyMap();
+ Y1 j1 a2 @$ @: L% \* H+ {
4 M2 e o7 F* @! o3 V" X/ d- // Setting a value
% s2 _) B% h6 w; u* F - fizz.set(68, 0);
3 B4 C6 g0 Y; D7 Q( e% G& B' _ - & e5 m* N6 E; C+ Y
- // Getting the value by its key3 X$ q: O& h" K% N6 W1 {. x" g
- let gotButUnsure: Int? = fizz.get(68); // returns Int or null, therefore the type is Int?1 `+ U* G" a* V4 R
- let mustHaveGotOrErrored: Int = fizz.get(68)!!; // explicitly asserting that the value must not be null,
! y' K4 ]( D( K; W5 T7 }, s - // which may crush at runtime if the value is, in fact, null _ k6 T7 V7 C: n5 _
- ' ]$ [% C0 E; ^$ Y# e9 F9 W# J4 M
- // Alternatively, we can check for the key in the if statement
9 [; E0 H8 j6 G2 `$ P+ E& j - if (gotButUnsure != null) {9 F$ \& Q4 r! [2 B$ [3 l
- // Hooray, let's use !! without fear now and cast Int? to Int \( F5 ]( D9 E5 f+ t( n
- let definitelyGotIt: Int = fizz.get(68)!!;1 ~- D' g: W& V
- } else {
! A5 b0 M, F2 k. n4 a( l% R" B+ O: { - // Do something else...# |0 P7 l( E4 a9 N) u$ \/ f5 P/ A2 z5 o l
- }
复制代码
( C/ }+ a1 ]2 W; @2 I9 Q A4 R
6 ^& G, U6 N1 S; w. Y3 H* ~* P3 R" _! I, V9 ]- s0 {3 E
# P0 }! a! ?; u( C: d5 A
0 t$ ~' e' {% ?8 L |
|