ハイパーニートプログラマーへの道

頑張ったり頑張らなかったり

【Swift】いろいろやってみる2

Dictionaryを空っぽにする

前回の記事の続きで

119> scores = [:]
120> println(scores)
[:]
121> scores.count
$R38: Int = 0
122> println("The dictionary of scores contains \(scores.count) items.")
The dictionary of scores contains 0 items.

Dictionaryを空にする場合は、[:](コロン忘れず)
[:]が表示されるんで一瞬?になるが、countで要素数取得すると、ちゃんとアイテム数は0になってる。

123> let emptyArray = String[]()
emptyArray: String[] = size=0
124> let emptyDictinary = Dictionary<String, Float>
                     ^
<REPL>:124:47: note: add arguments after the type to construct a value of the type
let emptyDictinary = Dictionary<String, Float>
                                              ^
                                              ()
<REPL>:124:47: note: use '.self' to reference the type object
let emptyDictinary = Dictionary<String, Float>
                                              ^
                                              .self

124> let emptyDictinary = Dictionary<String, Float>.self
emptyDictinary: Dictionary<String, Float>.Type = {
  _variantStorage = Native {
    Native = {
      Swift._NativeDictionaryStorageOwnerBase = <parent is NULL>

      nativeStorage = <parent is NULL>

    }
  }
}
125> let emptyDictinary = Dictionary<String, Float>()
emptyDictinary: Dictionary<String, Float> = {}

初期化。最後に()をつけなきゃいけない。124行目でのDictionary作成のときに忘れてしまって怒られる。
.self使って参照してみ、みたいなことも言われてるのでやってみる。よくわからんがいろいろ出てきた。

参考にした記事

Tumbling Dice — [Swift]Appleの新言語「Swift」のリファレンスを読む(3)

The Swift Programming Language: Collection Types

for-in

126> let individualScores = [75, 43, 103, 87, 12]
individualScores: Int[] = size=5 {
  [0] = 75
  [1] = 43
  [2] = 103
  [3] = 87
  [4] = 12
}
127> var teamScore = 0
teamScore: Int = 0
128> for score in individualScores {
129.     if score > 50 {
130.         teamScore += 3
131.     } else {
132.         teamScore += 1
133.     }
134. }   
135> teamScore
$R40: Int = 11
136> 

コードは The Swift Programming Language: A Swift Tour より。

individualScoresに5つのスコアをセットして、var teamScoreは0で初期化。
for-inでイテレート。要素を一つ一つ条件分岐にかけていって、スコアが51点以上だったらチームスコアに+3点、50点以下だったら+1点。
51点以上のスコアは3つあるので、3×3=9。50点以下のスコアは2つあるので、2×1=2。合計11点。
そろそろコマンドラインではきつくなってきたぞw