Created
November 9, 2016 11:27
-
-
Save laiso/334b12b3651ed42b1df06a132f9c671f to your computer and use it in GitHub Desktop.
Himotokiのがエラーの扱いが柔軟そうだなぁという印象 https://twitter.com/laiso/status/796225531179978752 #CodePiece
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
import Gloss | |
import Himotoki | |
struct GlossObject: Gloss.Decodable { | |
let name: String? | |
public init?(json: JSON) { | |
self.name = "name" <~~ json | |
} | |
} | |
struct HimotokiObject: Himotoki.Decodable { | |
let name: String | |
public static func decode(_ e: Extractor) throws -> HimotokiObject { | |
return try HimotokiObject( | |
name: e <| "name" | |
) | |
} | |
} | |
class ViewController: UIViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
do { | |
let source = "{\"name\": \"natasha\"}" | |
let JSON = try JSONSerialization.jsonObject(with: source.data(using: .utf8)!, options: .allowFragments) as! [String: AnyObject] | |
guard let g = GlossObject(json: JSON) else { | |
print("error?") | |
return | |
} | |
print(g.name) // Optional("natasha") | |
let h = try HimotokiObject.decodeValue(JSON) | |
print(h.name) // natasha | |
} catch let DecodeError.custom(reason) { | |
print(reason) | |
abort() | |
} catch { | |
abort() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment