|
Maps复合类型 map<K, V> 用于将 K 类型的键与 V 类型的相应值关联起来例如,map<Int, Int> 使用 Int 类型作为其键和值:- O; S ~. Y. e* u7 o9 i" Z/ D( U$ P
- struct IntToInt {0 u- C9 x2 W' V9 \
- counters: map<Int, Int>;
/ j, b$ A8 R" O+ a& S - }
复制代码 6 u4 k. d( Q/ ?& F5 ?
7 _6 y" k) `% n/ h
) A4 l0 h/ w# a2 U% |: Z4 J9 }操作
+ W Z7 m% h7 }: }! VDeclare, emptyMap()
& }7 K6 B+ d+ N9 i5 f作为局部变量,使用标准库的 emptyMap() 函数:
# o# T6 H1 o0 H- u0 c" |) I2 ^- let fizz: map<Int, Int> = emptyMap();
. E$ c6 A$ I3 U" f. f - let fizz: map<Int, Int> = null; // identical to the previous line, but less descriptive
复制代码 作为 持久状态变量:- m) I1 c0 y" D( G9 s
- contract Example {
% y( [7 D& z, Z' K - fizz: map<Int, Int>; // Int keys to Int values
4 z- n B2 p0 w# S* x - init() {. Y( B: U0 x& z# u, P- `# _
- self.fizz = emptyMap(); // redundant and can be removed!
% O. o& f; G# V/ z9 ~ - }
' S2 p$ r D: T" s - }
复制代码 请注意,类型为 map<K, V> 的 持久状态变量 默认为空,不需要默认值,也不需要在 init() 函数中进行初始化。
; A1 E, s, P( ^/ {/ A
8 N0 E. E, E+ e% O" l' g% x! N/ j
% P" h U. M: ?, J5 @& f. q7 M/ H# I) z7 j7 R8 U8 j
设置值,.set()! ]5 c9 r% l* R; @' W' X5 c
要设置或替换键下的值,请调用 .set() 方法,所有 map 都可以使用该方法。
2 ~" f' J! F3 O) @3 q- // Empty map
! y' `, T% C+ a2 [6 J - let fizz: map<Int, Int> = emptyMap();
& p' N1 b- y# E4 v
3 S8 g- v A q0 H, m: A& P- // Setting a couple of values under different keys. ~, K! H7 y! J- [- o7 ] F6 }
- fizz.set(7, 7);
7 M: \" {7 K1 k% T+ Z8 N/ j0 M' h! \ - fizz.set(42, 42);
8 r( _4 H) M1 B& i
; \. `( n: E. F) @: p0 z) B5 J/ n- // Overriding one of the existing key-value pairs
: [& b0 A3 \/ }* t - fizz.set(7, 68); // key 7 now points to value 68
复制代码- // Empty map
0 ]; Z+ k, I& R# r) ?# h - let fizz: map<Int, Int> = emptyMap();, t8 t% y% d8 ]* O6 |% M6 b
- 6 u( I& x, z z8 d3 b) R
- // Setting a value5 P# Z0 f8 [0 ?" \0 S# R9 _* P% p$ ]1 E
- fizz.set(68, 0);5 t9 q& K0 a( y3 Q' j
- 2 S: r0 ~- g d6 H3 Q
- // Getting the value by its key7 @# v% k! @7 v+ X; Q
- let gotButUnsure: Int? = fizz.get(68); // returns Int or null, therefore the type is Int?
0 z5 E* D* T+ d8 g: r Z2 t1 ~/ W - let mustHaveGotOrErrored: Int = fizz.get(68)!!; // explicitly asserting that the value must not be null,
. L+ \" E: K% [: a1 F - // which may crush at runtime if the value is, in fact, null* r# U. w: a5 L( S
- , m$ U2 h: A: S/ D& P
- // Alternatively, we can check for the key in the if statement
! f# v% O" a0 g& l- e7 q - if (gotButUnsure != null) {+ q9 n+ |# l M
- // Hooray, let's use !! without fear now and cast Int? to Int
) \ m" ?' }: R$ ]& t. X; Z - let definitelyGotIt: Int = fizz.get(68)!!;; r5 ? C! Z; ?3 X. R
- } else {
2 F- n3 K. n& G! m+ s' t/ v, j6 y - // Do something else...
) x' `8 X8 s5 ? - }
复制代码 ; [/ k/ Q' N, @5 t/ a7 M
" V/ R& q- b3 N3 `( w& X+ H a& Z6 o- ?5 _+ V7 H( d
9 t R6 U% R+ k) e/ {
3 l; U/ p2 c0 R8 F: H |
|