Skip to content

Instantly share code, notes, and snippets.

@ukitaka
Created April 26, 2017 06:21
Show Gist options
  • Save ukitaka/275d43bfe439a06238079dcb632a9f89 to your computer and use it in GitHub Desktop.
Save ukitaka/275d43bfe439a06238079dcb632a9f89 to your computer and use it in GitHub Desktop.
型クラスライクなDecode.swift
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