import Foundation // MARK: - CastingError struct CastingError: Error { let fromType: Any.Type let toType: Any.Type init<FromType, ToType>(fromType: FromType.Type, toType: ToType.Type) { self.fromType = fromType self.toType = toType } } extension CastingError: LocalizedError { var localizedDescription: String { return "Can not cast from \(fromType) to \(toType)" } } extension CastingError: CustomStringConvertible { var description: String { return localizedDescription } } // MARK: - Data cast extensions extension Data { func toDictionary(options: JSONSerialization.ReadingOptions = []) throws -> [String: Any] { return try to(type: [String: Any].self, options: options) } func to<T>(type: T.Type, options: JSONSerialization.ReadingOptions = []) throws -> T { guard let result = try JSONSerialization.jsonObject(with: self, options: options) as? T else { throw CastingError(fromType: type, toType: T.self) } return result } } // MARK: - String cast extensions extension String { func asJSON<T>(to type: T.Type, using encoding: String.Encoding = .utf8) throws -> T { guard let data = data(using: encoding) else { throw CastingError(fromType: type, toType: T.self) } return try data.to(type: T.self) } func asJSONToDictionary(using encoding: String.Encoding = .utf8) throws -> [String: Any] { return try asJSON(to: [String: Any].self, using: encoding) } } // MARK: - Dictionary cast extensions extension Dictionary { func toData(options: JSONSerialization.WritingOptions = []) throws -> Data { return try JSONSerialization.data(withJSONObject: self, options: options) } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter