Skip to content

Instantly share code, notes, and snippets.

@ktanaka117
Created March 22, 2016 05:47
Show Gist options
  • Save ktanaka117/d5d455f849a1bfd288d8 to your computer and use it in GitHub Desktop.
Save ktanaka117/d5d455f849a1bfd288d8 to your computer and use it in GitHub Desktop.
// 非参照型を使って副作用の少ないコードに、かつタイプセーフにしたい = swifty!!!
hogehoge() { [weak self] data, response, error in
// guardすることでnilでないことを今後保証する
guard let data = data else { return }
guard let newArray = data["populations"] as? [Population] else { return }
// 中身がPopulation型であることを保証するarray(タイプセーフ)
var populationArray: [Population] = []
for item in newArray {
let dictionary: [String: AnyObject]
// とりあえずjsonの扱いはswiftyJSONな書き方してるけどお好みで。
// Populationはstructで書いてるのでinitで全部つっこむ。
// property代入したいときはstructの中身をvarで宣言する。
let population = Population(
year: dictionary["year"].intValue,
under14: dictionary["under14"].intValue,
between15to64: dictionary["between15to64"].intValue,
over65: dictionary["over65"].intValue,
sum: dictionary["sum"].intValue
)
populationArray.append(population)
}
guard let `self` = self else { reuturn }
// ぐぎぎぎぎぎぎぎぎぎ......
self._flex.itemsSource = populationArray
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment