Skip to content

Instantly share code, notes, and snippets.

@anirudhamahale
Created June 22, 2020 11:40
Show Gist options
  • Save anirudhamahale/7c1107d5d89e3e3f81d20311ae43cb6a to your computer and use it in GitHub Desktop.
Save anirudhamahale/7c1107d5d89e3e3f81d20311ae43cb6a to your computer and use it in GitHub Desktop.
extension String {
func toArray() throws -> [Any] {
guard let stringData = data(using: .utf16, allowLossyConversion: false) else { return [] }
guard let array = try JSONSerialization.jsonObject(with: stringData, options: .mutableContainers) as? [Any] else {
throw JSONError.notArray
}
return array
}
func toDictionary() throws -> [String: Any] {
guard let binData = data(using: .utf16, allowLossyConversion: false) else { return [:] }
guard let json = try JSONSerialization.jsonObject(with: binData, options: .allowFragments) as? [String: Any] else {
throw JSONError.notNSDictionary
}
return json
}
func urlEncode() -> String? {
return addingPercentEncoding(withAllowedCharacters: .allowedURLCharacterSet)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment