|
Maps复合类型 map<K, V> 用于将 K 类型的键与 V 类型的相应值关联起来例如,map<Int, Int> 使用 Int 类型作为其键和值:) C' q0 E0 d7 O+ z: n2 |
- struct IntToInt {
' H1 m. n5 _: R" d& { - counters: map<Int, Int>;
- Q, }+ {0 g4 U/ |3 l$ F4 A) R& @ - }
复制代码
' s4 i$ `. I2 [, O- o
. k9 J F# x: `2 [$ r0 e8 }0 O% c7 {2 \6 t: P
操作
( \1 |1 W5 `* h# YDeclare, emptyMap()/ ?2 X8 s% ?$ ~2 D' T+ _
作为局部变量,使用标准库的 emptyMap() 函数:
5 p, @' Y1 m4 N. ]- let fizz: map<Int, Int> = emptyMap(); o" V8 ?) M! w/ `8 j' G. n P l
- let fizz: map<Int, Int> = null; // identical to the previous line, but less descriptive
复制代码 作为 持久状态变量:! j6 @7 S2 ^' @+ }3 b7 v% A9 I
- contract Example {/ E$ M/ h; ?- l1 H, R) f, [- d
- fizz: map<Int, Int>; // Int keys to Int values
8 l; h. U7 U# ^1 u) q - init() {
* e" Y5 X, `9 ]) Q - self.fizz = emptyMap(); // redundant and can be removed!
- Q# c" }0 a* q" ` - }8 L& h- [% _6 S6 R0 l- s" r' d
- }
复制代码 请注意,类型为 map<K, V> 的 持久状态变量 默认为空,不需要默认值,也不需要在 init() 函数中进行初始化。
- l6 `% O6 t' G- s! U6 p
2 r' K1 s# ^! J5 ^& Q5 M% g# s+ E6 T( `$ x- l& B
* h6 y1 k" ~3 \1 n9 R* z* z设置值,.set()
" b) ~: `/ B' l9 L" {9 S9 B要设置或替换键下的值,请调用 .set() 方法,所有 map 都可以使用该方法。
7 o( q5 @9 Q; h9 ?/ C; _* e- // Empty map
: R) c/ W1 [2 S - let fizz: map<Int, Int> = emptyMap();
) x+ _: Y" d/ z8 d1 C& K
6 W9 S% V* e$ ]8 R- // Setting a couple of values under different keys
0 T, k/ l% D/ z$ F/ j- U - fizz.set(7, 7);3 @/ k! t5 b0 \1 u( H! e$ d
- fizz.set(42, 42);4 s5 _1 i- w N# |8 u4 W( D
* w d8 f" Z. u* i- // Overriding one of the existing key-value pairs+ G1 O7 V( p- H( b3 ?! j
- fizz.set(7, 68); // key 7 now points to value 68
复制代码- // Empty map/ S+ q8 ]+ i7 }2 y/ F9 w) ^/ c8 `
- let fizz: map<Int, Int> = emptyMap();
! @# L$ H& S% I4 F; R' h3 t( D
3 i; ^0 g- p; r: {- // Setting a value* `( p! W- ]/ \: _5 `- L
- fizz.set(68, 0);
- @/ Y+ t3 O$ W# s) v* X
# Q) w. g) d, W! h4 s- // Getting the value by its key
^: x1 G1 }* ]3 y: b$ Q3 w - let gotButUnsure: Int? = fizz.get(68); // returns Int or null, therefore the type is Int?. M" m) T7 P9 g. |9 j" g; ^
- let mustHaveGotOrErrored: Int = fizz.get(68)!!; // explicitly asserting that the value must not be null,- C; [) V/ U2 r$ b& i
- // which may crush at runtime if the value is, in fact, null: r6 D( D5 H# ~. e* u" p4 S
) s' a0 y$ d# X' J" M- // Alternatively, we can check for the key in the if statement* I. { S! o/ {$ `: f+ c, O( ]* v
- if (gotButUnsure != null) {
6 z7 F3 O) V6 {( l/ l - // Hooray, let's use !! without fear now and cast Int? to Int9 J2 W3 C0 m+ B/ {( q6 y" Z
- let definitelyGotIt: Int = fizz.get(68)!!;3 J" j* U1 e8 p' b, {" j" K
- } else {
! l+ x% G6 F) y6 y7 ^4 W' D& I - // Do something else..." ?, w7 V. b" J7 E; D8 v3 Y3 t
- }
复制代码 1 a( c' N+ P9 A' J( \' G
" F! t( [6 f8 l. t! B
" M7 G& n0 Y6 P$ E
9 v+ _- x0 x/ p% q: u
0 q% {3 b0 j% a: C |
|