Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Song のデータの型(Entity)を定義して持ち回したい #5

Closed
zdogma opened this issue Feb 21, 2017 · 0 comments · Fixed by #6
Closed

Song のデータの型(Entity)を定義して持ち回したい #5

zdogma opened this issue Feb 21, 2017 · 0 comments · Fixed by #6

Comments

@zdogma
Copy link
Owner

zdogma commented Feb 21, 2017

#1 (comment)

持ち回すデータの型(Entity)を定義する

ViewControllerのdataをSong型として定義してあげるとスッキリします。あとJSONマッピングをObjectMapperなどを使ってやるとJSONとEntity間の変換が見通しやすくなりますよ!

import ObjectMapper

struct Song: ImmutableMappable {
    let title: String
    let text: String
    let thumbnail_url: String
    let series: String
    let scene: String
    let singer: String
    let embed_movie_src: String

    init(map: Map) throws {
        title = try map.value("title")
        text = try map.value("text")
        thumbnail_url = try map.value("thumbnail_url")
        series = try map.value("series")
        scene = try map.value("scene")
        singer = try map.value("singer")
        embed_movie_src = try map.value("embed_movie_src")
    }
}
そんでSong型オブジェクトをSongListTableViewControllerとViewControllerで持ち回すようにするといいです。ローカルのJSONファイルから[Song]に変換するメソッドはたとえば次のようになります。

func loadSongs() throws -> [Song] {
    if
        let path = Bundle.main.path(forResource: "aikatsu_songs", ofType: "json"),
        let data = FileManager.default.contents(atPath: path) {
        let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! [[String: Any]]
        return try Mapper<Song>().mapArray(JSONArray: json)
    } else {
        // なにかがおかしいよエラー
        throw CustomError.somethingWrong
    }
}

// どっか別のファイルに定義してもよい
enum CustomError: Error {
  case somethingWrong
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant