Skip to content

Instantly share code, notes, and snippets.

@DimaVartanian
Created September 24, 2015 22:53
Show Gist options
  • Save DimaVartanian/a1c0e06ee2b3b852d394 to your computer and use it in GitHub Desktop.
Save DimaVartanian/a1c0e06ee2b3b852d394 to your computer and use it in GitHub Desktop.
ambiguous use of overload
//: Playground - noun: a place where people can play
import UIKit
enum ParseError: ErrorType
{
case MissingKey(key: String)
case TypeMismatch(expected: String, actual: String)
}
class AppleSauce
{
let sessionToken: String
let sessionKey: String
let sessionPoop: String?
init(sessionKey: String, sessionToken: String, sessionPoop: String?)
{
self.sessionKey = sessionKey
self.sessionToken = sessionToken
self.sessionPoop = sessionPoop
}
convenience init(JSON: [String : AnyObject?]) throws
{
do
{
let _sessionPoop: String? = try AppleSauce.extract(JSON, key:"session_poop")
let _sessionToken : String = try AppleSauce.extract(JSON, key:"session_token")
let _sessionKey : String = try AppleSauce.extract(JSON, key:"session_key")
self.init(sessionKey: _sessionKey, sessionToken: _sessionToken, sessionPoop: _sessionPoop)
}
catch let e
{
self.init(sessionKey: "", sessionToken: "", sessionPoop:"")
print("Error: \(e)")
throw e
}
}
class func extract<T>(JSON: [String : AnyObject?], key: String) throws -> T
{
do
{
if let value = JSON[key]
{
if let casted = value as? T
{
return casted
}
else
{
throw ParseError.TypeMismatch(expected: "\(T.self)", actual: "\(value.dynamicType)")
}
}
else
{
throw ParseError.MissingKey(key: key)
}
}
catch let e
{
throw e
}
}
class func extract<T>(JSON: [String : AnyObject?], key: String) throws -> T?
{
do
{
let value: T = try extract(JSON, key: key)
return value
}
catch ParseError.MissingKey
{
return nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment