Created
September 24, 2015 22:53
-
-
Save DimaVartanian/a1c0e06ee2b3b852d394 to your computer and use it in GitHub Desktop.
ambiguous use of overload
This file contains 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
//: 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