Skip to content

Instantly share code, notes, and snippets.

@akisute
Created July 15, 2015 09:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akisute/f38a34985ee4aca1e5ad to your computer and use it in GitHub Desktop.
Save akisute/f38a34985ee4aca1e5ad to your computer and use it in GitHub Desktop.
Small extension to use try-catch error handling in SwiftyJSON
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)
}
}
@giacomopiva
Copy link

Nice :)
Can you provide a little example on how to use it?
Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment