Skip to content

Instantly share code, notes, and snippets.

@oleksii-demedetskyi
Created December 26, 2015 11:44
Show Gist options
  • Save oleksii-demedetskyi/68f702e303919abdbf8b to your computer and use it in GitHub Desktop.
Save oleksii-demedetskyi/68f702e303919abdbf8b to your computer and use it in GitHub Desktop.
//: Playground - noun: a place where people can play
import UIKit
// Simple struct to be fullfilled from JSON
struct User {
let name: String
let age: Int
}
// Simple JSON response object
let response = [
"user" : [
"username" : "Foxy",
"age" : "18"
]
] as Dictionary<String, AnyObject>
// Simple way to do parsing
let user = response["user"] as! Dictionary<String, AnyObject>
User(
name: user["username"] as! String, // Dealing with casting
age: Int(user["age"] as! String)! // Type conversions
)
// Protocol of things that can convert to other things
// Any can convert to itself at least
protocol Convertable {
static func convert<T>(value: T) -> Self?
}
// Generic method that will return expected type.
extension Dictionary where Value: AnyObject {
func tryConvert<T : Convertable>(key: Key) -> T? {
return self[key].flatMap { T.convert($0) }
}
func convert<T : Convertable>(key: Key) -> T {
return tryConvert(key)!
}
}
// Convertable support
extension String : Convertable {
static func convert<T>(value: T) -> String? {
switch value {
// Identity conversion
case let string as String: return string
default: return nil}
}
}
extension Int : Convertable {
static func convert<T>(value: T) -> Int? {
switch value {
case let int as Int: return int
// Type conversion
case let string as String: return Int(string)
default: return nil}
}
}
// Usage with type casting
let user2 = User(
name: user.convert("username"),
age: user.convert("age")
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment