SlideShare a Scribd company logo
{"JSON, Swift and Type
Safety" : "It's a wrap"}
@gylphi @sketchytech
[Anthony Levings,
@sketchyTech]
Presented at SwiftSummit.com, 21 March 2015
NSDataNSDataif letNSData?NSData?
AnyObject?AnyObject?NSJSONSerializationNSDataNSData
NSArrayNSArray
AnyObject?AnyObject?
NSDictionaryNSDictionary
AnyObjectAnyObject AnyObjectAnyObject AnyObjectAnyObject
NSArrayNSArray
NSArrayNSArray
NSDictionaryNSDictionary
NSStringNSString
AnyObjectAnyObjectNSNumberNSNumber NSNullNSNull
Safety Last
“Smash and Grab”
var error:NSError?
if let jsonObject = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error)
as? [String: AnyObject] {
let count = jsonObject["resultCount"] as? Int
// casting value to Int
}
var error:NSError?
if let jsonObject = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) as?
[String: AnyObject] {
var jDict = jsonObject
jDict["resultCount"] = "string"
// change of type can happen easily
let jsonData = NSJSONSerialization.dataWithJSONObject(jDict, options: nil, error: nil)
}
Simple Safety
“Dream Data”
if the JSON you are receiving looks like this
{"key1":"value1","key2":"value2","key3":"value3"
}
or this
[1,2,3,4,5,6,6,7,8,9,10]
then you can simply write
if let dict = jsonObject as? Dictionary<String,String>
{ }
or this
if let dict = jsonObject as? [Int]
{ }
to achieve type safety, but this will rarely the case in
the real world and so rather than keep dreaming, we
have…
Safely Wrapped
enum with associated values
enum Value {
// enum cases
case StringType(String)
case NumberType(NSNumber)
case NullType(NSNull)
// collection types
case DictionaryType(Dictionary<String,Value>)
case ArrayType([Value])
}
And we then wrap each value of a received
[AnyObject] or [String: AnyObject] as the
initializer to our enum*
* working code available, ask me after if you’re interested
if let num = dictionary["key"]?.number { }
RATHER THAN THIS:
if let dict = jsonObj as? [String: AnyObject],
str = dict[“key”] as? NSNumber { }
We can then combine associated values with
computed variables to achieve this kind of syntax:
Argo (thoughtbot)
Swiftz (typelift)
json-swift (David Owens II)
Three GitHub Swift–JSON libraries that already use associated
value enums in their code:
Type Safety =
Empowerment
• restrict changes of type (e.g. through subscripting)
• prevent the return of AnyObject
• enable the compiler to better detect errors and assist the
programmer
• reduction in the amount of code to test types and return
values
• IT MAKES US THINK ABOUT TREATMENT OF JSON!
Potential Problems
The larger your model object, the longer the build takes [using
Argo]. This is an issue with the Swift compiler having trouble
working out all the nested type inference. While Argo works, it
can be impracticle for large objects. There is work being done on
a separate branch to reduce this time. (Tony DiPasquale,
thoughtbot)
https://robots.thoughtbot.com/parsing-embedded-json-and-arrays-in-swift
Argo
Wrapped on Demand
A possible solution
enum Value {
// enum cases
case StringType(String)
case NumberType(NSNumber)
case NullType(NSNull)
// collection types
case DictionaryType(JSONDictionary)
case ArrayType(JSONArray)
}
If we use a struct and an enum together we can leverage
stored values:
(1) the getter can wrap individual values on demand (not
in advance).
(2) changes and additions to stored values become
simplified
if let p = parsedJSON["results"]?.jsonArr,
d = p[0]?.jsonDict {
d["trackName"]?.str
}
parsedJSON["results"]?[0]?["trackName"] = "Something"
And setting:
Getting:
Using the struct approach we also have easier access to information like
which keys have String values, which have Number values, etc.
—- Dictionary —-
json.keysWithNumberValues
json.keysWithStringValues
—- Array ——-
json.isNumberArray
json.isStringArray
json.isMixedArray
json.removeAllNumbers()
json.removeAllStrings()
and other benefits of stored properties, which enums don’t enjoy.
Bespoke Handling of
Data
if let url = NSURL(string:"http://itunes.apple.com/search?term=b12&limit=40"),
data = NSData(contentsOfURL: url),
parsedJSON = JSONParser.parseDictionary(data),
iTD = iTunesData(dict: parsedJSON)
{
let tracks = map(iTD.results, {x in Track(dict:x.jsonDict)})
}
Bespoke Handling of Data
public struct iTunesData {
public var resultCount:Int {
return results.count
}
public var results:JSONArray
public init?(dict:JSONDictionary) { ... }
public subscript (index:Int) -> JSONDictionary? { ... }
public mutating func updateTrackDetails(track:Track) { ... }
public func outputJSON() -> NSData? { ... }
}
public struct Track {
public var trackName:String, collectionName:String, trackId:Int
public init?(dict:JSONDictionary?) {
if let tN = dict?["trackName"]?.str,
cN = dict?["collectionName"]?.str,
tI = dict?["trackId"]?.num {
trackName = tN
collectionName = cN
trackId = tI.integerValue
}
else {
return nil
}
}
}
Round-tripping bespoke
data
Track info
iTunesData
JSONParser
JSON in
JSON out
JSON (JavaScript Object Notation) is a lightweight
data-interchange format. It is easy for humans to read
and write. It is easy for machines to parse and
generate. It is based on a subset of the JavaScript
Programming Language, Standard ECMA-262 3rd
Edition - December 1999. JSON is a text format that is
completely language independent but uses conventions
that are familiar to programmers of the C-family of
languages, including C, C++, C#, Java, JavaScript,
Perl, Python, and many others. These properties make
JSON an ideal data-interchange language.

More Related Content

What's hot

Introduction Big Data and Hadoop
Introduction Big Data and HadoopIntroduction Big Data and Hadoop
Introduction Big Data and Hadoop
명신 김
 
Stripe CTF3 wrap-up
Stripe CTF3 wrap-upStripe CTF3 wrap-up
Stripe CTF3 wrap-up
Stripe
 
Scala
ScalaScala
Python Deserialization Attacks
Python Deserialization AttacksPython Deserialization Attacks
Python Deserialization Attacks
NSConclave
 
Node.js Deserialization
Node.js DeserializationNode.js Deserialization
Node.js Deserialization
NSConclave
 
Meetup slides
Meetup slidesMeetup slides
Meetup slides
suraj_atreya
 
JavaScript, TypeScipt and React Native
JavaScript, TypeScipt and React NativeJavaScript, TypeScipt and React Native
JavaScript, TypeScipt and React Native
Mitchell Tilbrook
 
【Unity】Scriptable object 入門と活用例
【Unity】Scriptable object 入門と活用例【Unity】Scriptable object 入門と活用例
【Unity】Scriptable object 入門と活用例
Unity Technologies Japan K.K.
 
Adopting Swift Generics
Adopting Swift GenericsAdopting Swift Generics
Adopting Swift Generics
Max Sokolov
 
Ts archiving
Ts   archivingTs   archiving
Ts archiving
Confiz
 
Clojure Intro
Clojure IntroClojure Intro
Clojure Intro
thnetos
 
Java 7
Java 7Java 7
Java 7
Bipul Sinha
 
Extending Node.js using C++
Extending Node.js using C++Extending Node.js using C++
Extending Node.js using C++
Kenneth Geisshirt
 
Getting Started with Datatsax .Net Driver
Getting Started with Datatsax .Net DriverGetting Started with Datatsax .Net Driver
Getting Started with Datatsax .Net Driver
DataStax Academy
 
MongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with MorphiaMongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with Morphia
Scott Hernandez
 
Effective testing for spark programs scala bay preview (pre-strata ny 2015)
Effective testing for spark programs scala bay preview (pre-strata ny 2015)Effective testing for spark programs scala bay preview (pre-strata ny 2015)
Effective testing for spark programs scala bay preview (pre-strata ny 2015)
Holden Karau
 
Functional Programming, simplified
Functional Programming, simplifiedFunctional Programming, simplified
Functional Programming, simplified
Naveenkumar Muguda
 
descriptive programming
descriptive programmingdescriptive programming
descriptive programming
Anand Dhana
 
Python Memory Management 101(Europython)
Python Memory Management 101(Europython)Python Memory Management 101(Europython)
Python Memory Management 101(Europython)
Jose Manuel Ortega Candel
 
State of GeoTools 2012
State of GeoTools 2012State of GeoTools 2012
State of GeoTools 2012
Jody Garnett
 

What's hot (20)

Introduction Big Data and Hadoop
Introduction Big Data and HadoopIntroduction Big Data and Hadoop
Introduction Big Data and Hadoop
 
Stripe CTF3 wrap-up
Stripe CTF3 wrap-upStripe CTF3 wrap-up
Stripe CTF3 wrap-up
 
Scala
ScalaScala
Scala
 
Python Deserialization Attacks
Python Deserialization AttacksPython Deserialization Attacks
Python Deserialization Attacks
 
Node.js Deserialization
Node.js DeserializationNode.js Deserialization
Node.js Deserialization
 
Meetup slides
Meetup slidesMeetup slides
Meetup slides
 
JavaScript, TypeScipt and React Native
JavaScript, TypeScipt and React NativeJavaScript, TypeScipt and React Native
JavaScript, TypeScipt and React Native
 
【Unity】Scriptable object 入門と活用例
【Unity】Scriptable object 入門と活用例【Unity】Scriptable object 入門と活用例
【Unity】Scriptable object 入門と活用例
 
Adopting Swift Generics
Adopting Swift GenericsAdopting Swift Generics
Adopting Swift Generics
 
Ts archiving
Ts   archivingTs   archiving
Ts archiving
 
Clojure Intro
Clojure IntroClojure Intro
Clojure Intro
 
Java 7
Java 7Java 7
Java 7
 
Extending Node.js using C++
Extending Node.js using C++Extending Node.js using C++
Extending Node.js using C++
 
Getting Started with Datatsax .Net Driver
Getting Started with Datatsax .Net DriverGetting Started with Datatsax .Net Driver
Getting Started with Datatsax .Net Driver
 
MongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with MorphiaMongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with Morphia
 
Effective testing for spark programs scala bay preview (pre-strata ny 2015)
Effective testing for spark programs scala bay preview (pre-strata ny 2015)Effective testing for spark programs scala bay preview (pre-strata ny 2015)
Effective testing for spark programs scala bay preview (pre-strata ny 2015)
 
Functional Programming, simplified
Functional Programming, simplifiedFunctional Programming, simplified
Functional Programming, simplified
 
descriptive programming
descriptive programmingdescriptive programming
descriptive programming
 
Python Memory Management 101(Europython)
Python Memory Management 101(Europython)Python Memory Management 101(Europython)
Python Memory Management 101(Europython)
 
State of GeoTools 2012
State of GeoTools 2012State of GeoTools 2012
State of GeoTools 2012
 

Similar to {"JSON, Swift and Type Safety" : "It's a wrap"}

Reversing JavaScript
Reversing JavaScriptReversing JavaScript
Reversing JavaScript
Roberto Suggi Liverani
 
droidparts
droidpartsdroidparts
droidparts
Droidcon Berlin
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
Sven Haiges
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기
Arawn Park
 
sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)
sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)
sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)
Eugene Yokota
 
Coding Ajax
Coding AjaxCoding Ajax
Coding Ajax
Ted Husted
 
Java
JavaJava
Dynamic Python
Dynamic PythonDynamic Python
Dynamic Python
Chui-Wen Chiu
 
Typescript - why it's awesome
Typescript - why it's awesomeTypescript - why it's awesome
Typescript - why it's awesome
Piotr Miazga
 
JavaScript Foundations Day1
JavaScript Foundations Day1JavaScript Foundations Day1
JavaScript Foundations Day1
Troy Miles
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
Łukasz Bałamut
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and Monoids
Hugo Gävert
 
iPhone Development Intro
iPhone Development IntroiPhone Development Intro
iPhone Development Intro
Luis Azevedo
 
JavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingJavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft Training
Radoslav Georgiev
 
Coding Ajax
Coding AjaxCoding Ajax
Coding Ajax
Ted Husted
 
Kotlin coroutines and spring framework
Kotlin coroutines and spring frameworkKotlin coroutines and spring framework
Kotlin coroutines and spring framework
Sunghyouk Bae
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
Ricardo Silva
 
Automated Discovery of Deserialization Gadget Chains
 Automated Discovery of Deserialization Gadget Chains Automated Discovery of Deserialization Gadget Chains
Automated Discovery of Deserialization Gadget Chains
Priyanka Aash
 
Screaming fast json parsing on Android
Screaming fast json parsing on AndroidScreaming fast json parsing on Android
Screaming fast json parsing on Android
Karthik Ramgopal
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
Stuart Roebuck
 

Similar to {"JSON, Swift and Type Safety" : "It's a wrap"} (20)

Reversing JavaScript
Reversing JavaScriptReversing JavaScript
Reversing JavaScript
 
droidparts
droidpartsdroidparts
droidparts
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기
 
sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)
sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)
sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)
 
Coding Ajax
Coding AjaxCoding Ajax
Coding Ajax
 
Java
JavaJava
Java
 
Dynamic Python
Dynamic PythonDynamic Python
Dynamic Python
 
Typescript - why it's awesome
Typescript - why it's awesomeTypescript - why it's awesome
Typescript - why it's awesome
 
JavaScript Foundations Day1
JavaScript Foundations Day1JavaScript Foundations Day1
JavaScript Foundations Day1
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and Monoids
 
iPhone Development Intro
iPhone Development IntroiPhone Development Intro
iPhone Development Intro
 
JavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingJavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft Training
 
Coding Ajax
Coding AjaxCoding Ajax
Coding Ajax
 
Kotlin coroutines and spring framework
Kotlin coroutines and spring frameworkKotlin coroutines and spring framework
Kotlin coroutines and spring framework
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
 
Automated Discovery of Deserialization Gadget Chains
 Automated Discovery of Deserialization Gadget Chains Automated Discovery of Deserialization Gadget Chains
Automated Discovery of Deserialization Gadget Chains
 
Screaming fast json parsing on Android
Screaming fast json parsing on AndroidScreaming fast json parsing on Android
Screaming fast json parsing on Android
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
 

Recently uploaded

Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Tatiana Kojar
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
Wouter Lemaire
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - HiikeSystem Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
Hiike
 
Trusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process MiningTrusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process Mining
LucaBarbaro3
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Wask
 
Operating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptxOperating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptx
Pravash Chandra Das
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
Azure API Management to expose backend services securely
Azure API Management to expose backend services securelyAzure API Management to expose backend services securely
Azure API Management to expose backend services securely
Dinusha Kumarasiri
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 

Recently uploaded (20)

Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - HiikeSystem Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
 
Trusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process MiningTrusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process Mining
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
 
Operating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptxOperating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptx
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
Azure API Management to expose backend services securely
Azure API Management to expose backend services securelyAzure API Management to expose backend services securely
Azure API Management to expose backend services securely
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 

{"JSON, Swift and Type Safety" : "It's a wrap"}

  • 1. {"JSON, Swift and Type Safety" : "It's a wrap"} @gylphi @sketchytech [Anthony Levings, @sketchyTech] Presented at SwiftSummit.com, 21 March 2015
  • 8. var error:NSError? if let jsonObject = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) as? [String: AnyObject] { let count = jsonObject["resultCount"] as? Int // casting value to Int }
  • 9. var error:NSError? if let jsonObject = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) as? [String: AnyObject] { var jDict = jsonObject jDict["resultCount"] = "string" // change of type can happen easily let jsonData = NSJSONSerialization.dataWithJSONObject(jDict, options: nil, error: nil) }
  • 11. if the JSON you are receiving looks like this {"key1":"value1","key2":"value2","key3":"value3" } or this [1,2,3,4,5,6,6,7,8,9,10]
  • 12. then you can simply write if let dict = jsonObject as? Dictionary<String,String> { } or this if let dict = jsonObject as? [Int] { } to achieve type safety, but this will rarely the case in the real world and so rather than keep dreaming, we have…
  • 13. Safely Wrapped enum with associated values
  • 14. enum Value { // enum cases case StringType(String) case NumberType(NSNumber) case NullType(NSNull) // collection types case DictionaryType(Dictionary<String,Value>) case ArrayType([Value]) }
  • 15. And we then wrap each value of a received [AnyObject] or [String: AnyObject] as the initializer to our enum* * working code available, ask me after if you’re interested
  • 16. if let num = dictionary["key"]?.number { } RATHER THAN THIS: if let dict = jsonObj as? [String: AnyObject], str = dict[“key”] as? NSNumber { } We can then combine associated values with computed variables to achieve this kind of syntax:
  • 17. Argo (thoughtbot) Swiftz (typelift) json-swift (David Owens II) Three GitHub Swift–JSON libraries that already use associated value enums in their code:
  • 18. Type Safety = Empowerment • restrict changes of type (e.g. through subscripting) • prevent the return of AnyObject • enable the compiler to better detect errors and assist the programmer • reduction in the amount of code to test types and return values • IT MAKES US THINK ABOUT TREATMENT OF JSON!
  • 20. The larger your model object, the longer the build takes [using Argo]. This is an issue with the Swift compiler having trouble working out all the nested type inference. While Argo works, it can be impracticle for large objects. There is work being done on a separate branch to reduce this time. (Tony DiPasquale, thoughtbot) https://robots.thoughtbot.com/parsing-embedded-json-and-arrays-in-swift Argo
  • 21. Wrapped on Demand A possible solution
  • 22. enum Value { // enum cases case StringType(String) case NumberType(NSNumber) case NullType(NSNull) // collection types case DictionaryType(JSONDictionary) case ArrayType(JSONArray) }
  • 23. If we use a struct and an enum together we can leverage stored values: (1) the getter can wrap individual values on demand (not in advance). (2) changes and additions to stored values become simplified
  • 24. if let p = parsedJSON["results"]?.jsonArr, d = p[0]?.jsonDict { d["trackName"]?.str } parsedJSON["results"]?[0]?["trackName"] = "Something" And setting: Getting:
  • 25. Using the struct approach we also have easier access to information like which keys have String values, which have Number values, etc. —- Dictionary —- json.keysWithNumberValues json.keysWithStringValues —- Array ——- json.isNumberArray json.isStringArray json.isMixedArray json.removeAllNumbers() json.removeAllStrings() and other benefits of stored properties, which enums don’t enjoy.
  • 27. if let url = NSURL(string:"http://itunes.apple.com/search?term=b12&limit=40"), data = NSData(contentsOfURL: url), parsedJSON = JSONParser.parseDictionary(data), iTD = iTunesData(dict: parsedJSON) { let tracks = map(iTD.results, {x in Track(dict:x.jsonDict)}) } Bespoke Handling of Data
  • 28. public struct iTunesData { public var resultCount:Int { return results.count } public var results:JSONArray public init?(dict:JSONDictionary) { ... } public subscript (index:Int) -> JSONDictionary? { ... } public mutating func updateTrackDetails(track:Track) { ... } public func outputJSON() -> NSData? { ... } }
  • 29. public struct Track { public var trackName:String, collectionName:String, trackId:Int public init?(dict:JSONDictionary?) { if let tN = dict?["trackName"]?.str, cN = dict?["collectionName"]?.str, tI = dict?["trackId"]?.num { trackName = tN collectionName = cN trackId = tI.integerValue } else { return nil } } }
  • 32. JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

Editor's Notes

  1. Slides to accompany Box demo
  2. There is nothing to stop us ignoring type safety and working with the JSON objects without a care for type beyond an adherence to the AnyObject protocol.
  3. before you can use a value in any meaningful way it must be cast to a type in Swift
  4. We are flexible to change values paying no regard to type. Here the resultCount is changed from a number to a string.
  5. JSON is characteristically mixed in types and it unless the data was preprepared with strong typing in mind it would be unusual for JSON to be treated in this way
  6. Then you have a very simple situation
  7. You can transform what you have into a Swift Dictionary or Array and be done with it.
  8. JSON is characteristically mixed in types and it unless the data was preprepared with strong typing in mind it would be unusual for JSON to be treated in this way, so how do we co-exist with this while still respecting Swift’s strong typing. The answer is enums with associated values.
  9. This is what the cases look like if we wrap all values and NullType probably doesn’t need a NSNull inside because NSNull is always the same. One their own they can wrap everything and provide us with a type safe way to access values.
  10. enums allow us to escape the world of AnyObject and use a neater looking syntax when paired with computed variables.
  11. enums allow us to escape the world of AnyObject and use a neater looking syntax when paired with computed variables.
  12. Note the omission of SwiftyJSON, which uses enums (without associated values) in unison with a stored AnyObject type property
  13. JSON is characteristically mixed in types and it unless the data was preprepared with strong typing in mind it would be unusual for JSON to be treated in this way
  14. JSON is characteristically mixed in types and it unless the data was preprepared with strong typing in mind it would be unusual for JSON to be treated in this way
  15. This might not be due to the wrapping but other elements of the approach.
  16. JSON is characteristically mixed in types and it unless the data was preprepared with strong typing in mind it would be unusual for JSON to be treated in this way
  17. What if instead of using Dictionary and Array we created unique JSONDictionary and JSONArray types? Would a struct that wrapped on demand, instead of storing wrapped values, save time wrapping and unwrapping? And how would it work? One idea that I’ve worked on is to internally store five dictionaries corresponding to the cases. In the dictionary these are of type [String: String], [String: NSNumber], [String: NSNull], [String: JSONDictionary], [String: JSONArray] and internally the JSONArray type has similar dictionaries but using Int as its key. This approach makes it very easy to add and change values, to return all strings or numbers, to see at a glance whether arrays contain only strings or only numbers, and so on. It is made possible by the ability of structs to store property values.
  18. While we can access all values from the parsed JSON, we can also build bespoke ways of handling the parsed JSON making it easier to manipulate and we could drill down even further if we wished.
  19. Remember to have MAMP on for demo, Dropbox/SwiftSummit/SwiftSummit_JSON_Presentation_Struct.Playground Document/Developer/Swift/JSONParser