|
Maps复合类型 map<K, V> 用于将 K 类型的键与 V 类型的相应值关联起来例如,map<Int, Int> 使用 Int 类型作为其键和值:) H4 b C1 \ s% V0 r
- struct IntToInt {
+ c: `& ~$ W$ {* t - counters: map<Int, Int>;- g9 [, e( l% l
- }
复制代码
- v+ x" m- q' t2 Y; M' W R
) q* w" Y& G) [' A
* h% K+ w4 o3 C! x1 P2 J操作
: E2 ~/ C& K4 l# Z0 N$ s- R' W: Z7 q3 jDeclare, emptyMap()
! W, h8 I, f( p6 j9 U: ]作为局部变量,使用标准库的 emptyMap() 函数:$ A# o. N, r% S( Y6 Z1 `
- let fizz: map<Int, Int> = emptyMap();
' S1 t4 h" s7 M j( p6 `, Q8 ` - let fizz: map<Int, Int> = null; // identical to the previous line, but less descriptive
复制代码 作为 持久状态变量:
& E( M- y& t) l5 S- g- contract Example {3 U* h i1 C8 R7 E+ j
- fizz: map<Int, Int>; // Int keys to Int values6 a4 z w& J# P, o8 o
- init() {- c- [5 f3 B$ c% S- U1 Z
- self.fizz = emptyMap(); // redundant and can be removed!) g; p# s; |7 G# c; {
- }
2 W# _- A% d0 F% O$ q% c1 @1 t - }
复制代码 请注意,类型为 map<K, V> 的 持久状态变量 默认为空,不需要默认值,也不需要在 init() 函数中进行初始化。
3 a$ c$ i: q {8 M7 `# X) @6 i, |7 Q; ` G f, U
& E3 S, M& B, \2 J
/ D9 N, _! |& S& q设置值,.set()% n9 T! A% G, w
要设置或替换键下的值,请调用 .set() 方法,所有 map 都可以使用该方法。
. a# a$ t+ ^1 \ q- // Empty map7 `$ G! R3 A' Q2 P8 F: U% |
- let fizz: map<Int, Int> = emptyMap();
% _% {3 {# V6 V) ^: K - ; k5 D2 W0 E& m4 K5 i- s8 p7 n& g1 i
- // Setting a couple of values under different keys7 ~/ @8 f) o9 g, _7 |
- fizz.set(7, 7);+ e; E: q% H% ]' F( s C/ U
- fizz.set(42, 42);& S" N; M& I9 a4 D1 _6 f
4 v! N/ s6 ?0 y! r- // Overriding one of the existing key-value pairs8 S( |& C* J! X( I; p |+ h
- fizz.set(7, 68); // key 7 now points to value 68
复制代码- // Empty map
$ t- }" [# S" y8 }" D- j* j - let fizz: map<Int, Int> = emptyMap();- C4 i) u5 O4 y0 X1 w' r* u
- ) P' @# r: P" \$ P4 P4 Q
- // Setting a value# f, q6 J* F% n& Y' S
- fizz.set(68, 0);
- |; T; a9 F9 G
. M% y9 x9 l* J! H$ d" H& i- // Getting the value by its key/ V0 d1 m+ v, H- `4 g. z
- let gotButUnsure: Int? = fizz.get(68); // returns Int or null, therefore the type is Int?. Z" `) P4 s2 }1 [- l; l
- let mustHaveGotOrErrored: Int = fizz.get(68)!!; // explicitly asserting that the value must not be null,# d9 O/ h. u4 b# i+ D
- // which may crush at runtime if the value is, in fact, null
9 q [, _* h3 }. F5 _
* L. e# c% v$ \" a* ]; v- // Alternatively, we can check for the key in the if statement3 B. d, r* @; R: t/ _0 k) L
- if (gotButUnsure != null) {
" r: J: r7 } u - // Hooray, let's use !! without fear now and cast Int? to Int
' r! G. t3 s: Q0 ^: A- E# o - let definitelyGotIt: Int = fizz.get(68)!!;" X9 X1 y; g" m7 \! w
- } else {
/ y' Z9 _# L9 {# b2 k* S - // Do something else...# ^; x# |0 T1 i# h2 z6 y6 y9 W
- }
复制代码
2 e8 f$ x/ D% K, v5 c7 y- l: _, l0 E/ U9 m
- ^' i2 C8 t5 Y, v5 H
0 d7 Q- }: r/ q1 Z# p# I% h$ o
7 K6 l8 ~8 z) K2 G0 l# \% [ |
|