Created
July 15, 2015 09:30
-
-
Save akisute/f38a34985ee4aca1e5ad to your computer and use it in GitHub Desktop.
Small extension to use try-catch error handling in SwiftyJSON
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 Foundation | |
public enum JSONError: Int, ErrorType { | |
case UnsupportedType = 999 | |
case IndexOutOfBounds = 900 | |
case WrongType = 901 | |
case ErrorNotExist = 500 | |
} | |
public extension JSON { | |
public func tryGet<T>(@autoclosure f: () -> T?) throws -> T { | |
guard let value = f() else { | |
throw JSONError.WrongType | |
} | |
return value | |
} | |
public func tryBool() throws -> Bool { | |
return try self.tryGet(self.bool) | |
} | |
public func tryString() throws -> String { | |
return try self.tryGet(self.string) | |
} | |
public func tryNumber() throws -> NSNumber { | |
return try self.tryGet(self.number) | |
} | |
public func tryURL() throws -> NSURL { | |
return try self.tryGet(self.URL) | |
} | |
public func tryDouble() throws -> Double { | |
return try self.tryGet(self.double) | |
} | |
public func tryFloat() throws -> Float { | |
return try self.tryGet(self.float) | |
} | |
public func tryInt() throws -> Int { | |
return try self.tryGet(self.int) | |
} | |
public func tryUInt() throws -> UInt { | |
return try self.tryGet(self.uInt) | |
} | |
public func tryInt64() throws -> Int64 { | |
return try self.tryGet(self.int64) | |
} | |
public func tryUInt64() throws -> UInt64 { | |
return try self.tryGet(self.uInt64) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice :)
Can you provide a little example on how to use it?
Thank you.