Created
April 26, 2017 06:21
-
-
Save ukitaka/275d43bfe439a06238079dcb632a9f89 to your computer and use it in GitHub Desktop.
型クラスライクなDecode.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
typealias JSON = [String:String] | |
protocol Decoder { | |
associatedtype T | |
func decode(json: JSON) -> T | |
} | |
protocol Decodable { | |
static func decode<D: Decoder>(json: JSON, decoder: D) -> D.T where D.T == Self | |
} | |
extension Decodable { | |
static func decode<D: Decoder>(json: JSON, decoder: D) -> D.T where D.T == Self { | |
return decoder.decode(json: json) | |
} | |
} | |
class A { | |
let a: String | |
init(a: String) { | |
self.a = a | |
} | |
} | |
class B: A { | |
let b: String | |
init(a: String, b: String) { | |
self.b = b | |
super.init(a: a) | |
} | |
} | |
extension A: Decodable { } | |
let json: JSON = ["a":"AAAAA", "b": "BBBBB"] | |
struct ADecoder: Decoder { | |
func decode(json: JSON) -> A { | |
return A(a: json["a"]!) | |
} | |
} | |
struct BDecoder: Decoder { | |
func decode(json: JSON) -> B { | |
return B(a: json["a"]!, b: json["b"]!) | |
} | |
} | |
let a = A.decode(json: json, decoder: ADecoder()) | |
//NG | |
//let b_with_a_decoder = B.decode(json: json, decoder: ADecoder()) | |
let b = B.decode(json: json, decoder: BDecoder()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment