Вы находитесь на странице: 1из 21

http://roadfiresoftware.

com/2014/04/how-to-become-a-professional-ios-developer/

How to become a professional iOS developer


Published by Josh Brown on April 10, 2014

If you’re wondering how you can become a professional iOS developer, here’s what I’d
recommend you do, in this order. I speak from (a) my professional experience in 4 years as an
iOS consultant and 7 years as a software developer and (b) as a hiring manager – I’ve hired
several iOS developers over the last 2 years to handle overflow work that I’m too busy to do.
These are the things I look for when hiring an iOS developer. The order here is important – each
subsequent step builds on the previous – and in some cases, the earlier ones are a prerequisite to
later ones (as in absolutely essential).

1. Learn software craftsmanship


There are lots of terms to describe the way software is built. I’m choosing software
craftsmanship, but the term is irrelevant. You should know how to build software well – how to
structure it well, how to test, how to debug, and how to use source control, at a bare minimum. If
you don’t feel comfortable with these practices yet, you should learn them now, before moving
on. I’d recommend reading The Pragmatic Programmer to get started.

2. Learn how to use source control


Source control is so important that I’m going to mention it twice. Yes, it’s part of software
craftsmanship, and yes, it’s important enough to get its own section. If you’re going to be
working with another iOS developer (and even if you’re not), you absolutely need to know how
to use source control. It gives you the ability to make checkpoints, go back in time to a previous
version of your code base, and explain why you’re making a given change. It’s likely that you’ll
be using git, as so many companies are nowadays, but you can check the job description to see
what they use. For git, you should know:

 how to initialize a repo


 how to clone a repo
 how to commit and push to a remote
 how to pull and merge changes from a remote
 how to check the status of your local repo
 how (and when) to create and merge branches
 how to create tags (you should do this every time you submit to Apple – at a minimum)

These are the basics – there’s much more you can do with git, and you can (and should) learn
more as you go. If you don’t already know git, you can start learning it at try.github.io.

3. Learn Objective-C
Perhaps this is a given, but if you want to do professional iOS development, you need to know
Objective-C. For a junior level position, you should at least know the syntax and a good deal of
the Foundation framework (objects, collections, data types, networking, JSON). In addition to
this, you need to know basic object-oriented concepts, like what an object is, what a class is, and
how to write methods.

You can learn a bit about objects in Objective-C (via unit tests!) with this screencast. And you
can learn even more in our iOS Boot Camp.

4. Learn iOS
Again, this is probably a given. If you want to be a professional iOS developer, you have to know
iOS. This means you should have a good grasp of how to:

 build views (with Storyboards, xibs, or programmatically – bonus points for knowing all
three)
 handle user interaction via various controls (buttons, switches, sliders, etc.)
 display data in a table view
 show alerts
 handle navigation and transition between views
 display images, labels, and text views
 create scroll views with various UI elements

You should also know about the view controller lifecycle, and when various methods are called
on UIViewController (viewDidLoad, viewWillAppear, etc.). Our iOS Boot Camp is designed to
teach you most of these.

5. Build an app
If you’ve actually built an app, you’ve proven that you know how to build an app. And if you
know how to build an app, you’re much more valuable to a potential employer than someone who
says they know Objective-C and iOS but hasn’t actually built anything. Prove you know what
you’re doing by building a real app.

This one comes after learning how to use source control for a reason – now that you know how to
use source control, use it while you build your own app. You’ll have a much better idea of what
files should be ignored and which ones shouldn’t if you’ve actually used source control on an iOS
project.

6. (Optional, but highly recommended) Publish your app to


the App Store
I’m making this optional because for some employers, you may not need to submit an app to
Apple – there may be a senior dev on the team who’s handling it or they may only be distributing
the app internally. But since you may need to publish your future employer’s app to the App
Store, you should know how the process works. And there’s no better way to learn than by doing
it yourself. Even if there’s a senior developer on the team who’s responsible for submitting the
app to Apple, there may be times when you need to login to iTunes Connect to take care of
updating metadata, releasing an update, or a host of other things. Do this, and you’ll prove to
your future employer that you can take an idea to the App Store.

7. Apply for jobs and show what you can do for them
If you want to do iOS professionally, you’ll need to apply for a job at some point. But before you
do, think about why a company would want to hire you. Go ahead – I’ll wait… Got an answer
yet? Here it is: they want to make money from you. They want to sell your work and bring in
more money than they spend on you. Or, if they’re looking to cut costs, they want to save more
money than they spend on you. Helping a client (or your employer) reach their goals is actually
the topic of an entire book, which you should definitely read if you’re freelancing.

So your job is to convince your prospective client/employer that:

 you can get work done in a timely manner


 you can get work done within their budget
 you can help them reach their business goals (i.e. make more money)

Most companies won’t even ask you about this stuff. They might do a technical interview and a
personality interview to see if you’re a good fit and can help them. But if you understand that
they want to make money from your work and you can clearly communicate how you’ll be able
to do that, you’re much more likely to get hired. Showing them your iOS work is one way you
can do this – you’re proving to them that you can get things done.

There’s a lot to do. Want some help getting there?


If you know software craftsmanship and how to use source control but you’re not comfortable
with Objective-C and iOS – or you just haven’t built your first app – you might be interested in
our one-day iOS Boot Camp. It’s designed to get you past the painful parts of starting: those tiny
syntax errors you spend hours hunting down and all that time you waste learning the old way of
doing things. It’s just the good stuff, the relevant stuff, the important stuff – and of course, you
can ask questions live and get me to hunt down your syntax errors. :)

Be the first to hear about the next iOS Boot Camp:


http://roadfiresoftware.com/2014/05/five-great-reasons-to-learn-ios-and-objective-c/

Five Great Reasons to Learn iOS and


Objective-C
Published by Josh Brown on May 6, 2014

If you’ve thought about learning iOS and Objective-C, have you thought about why you want to
learn? What do you want to do with that knowledge? Are you hoping to stay relevant? Put an app
on the App Store? Show your friends what you can do? If you’re not sure, here are five great
reasons to learn iOS and Objective-C.

1. You want to invest regularly in your knowledge portfolio. You know that in order to be a
great developer, you need to be learning all the time. And you understand that learning a new
language helps you to see the world differently and makes you a better developer – even if you
continue using the same language in your everyday work.

2. You want to stay relevant. Maybe you currently write code in a language that’s on the
decline, and you want to make sure you have the skills you need in order to continue to be
indispensable to your employer. You know that Objective-C is on the rise as Java slowly
declines, and learning Objective-C would ensure that you still have the skills employers are
looking for.

3. You want to build an app & sell it on the App Store. Maybe you have a great idea that you
just can’t wait to build, and you want to sell it on the App Store and start making some money on
it. You know that using PhoneGap will result in an app that’s sluggish and doesn’t have the feel
of a native app – so you want to build a native app with Objective-C and iOS.

4. You’re ready to take your career a different direction. Perhaps you want to make a living
on Objective-C and iOS. After I learned iOS in my spare time, I was able to start freelancing and
eventually grow my business into a small consultancy. Learning iOS gave me the freedom to
work with the technology I wanted (Macs, iPhones, and iPads), leave the shackles of salaried
employment, and build the business and lifestyle I wanted.

5. You want to be able to show off your work. Maybe you work as a backend developer now
and still can’t get your friends and family to understand what you do. You want to work on apps
that you can show them by pulling your phone out of your pocket and saying “I made this.”
You’d like to build something they can see in the App Store and install on their phone.

Are you ready to learn iOS and Objective-C? Enter your email below and grab my advice, tips,
and tutorials on iOS development designed to help you become a master of iOS development –
and never worry about whether you’ll be stuck maintaining legacy Java for the rest of your life.
Plus, you’ll get to hear more about our upcoming iOS Boot Camp, which is designed to help you
get started with iOS quickly – without pulling your hair out.
http://roadfiresoftware.com/2014/09/how-to-use-git-for-ios-projects/

How to use git for iOS projects


Published by Josh Brown on September 2, 2014

When I’m working on a team, my preferred workflow is to use feature branches and pull requests
with git. This comes largely from Scott Chacon’s article called GitHub Flow, though I’ve adapted
it somewhat for iOS development.

1. Anything in the master branch is good enough to build and send out to testers
2. To work on something new, create a descriptively named branch off of master (ie: fix-
search or add-barcode-scanning)
3. Commit to that branch locally and regularly push your work to the same named branch on
the server
4. When you think the branch is ready to merge into master, create a pull request
5. After someone else has reviewed and signed off on the pull request, you can merge it into
master

If you read Scott’s article, you’ll note that I removed his point about how you can and should
deploy master immediately after a merge. We do a new build of the app for our testers every
week, so we just build from master and send it to our testers every Friday. In the iOS world, I
think it makes less sense to build and deploy immediately after merging. For us, that would result
in at least a build a day, and often multiple builds per day – and our testers need to download and
install each one. To me, immediate deploys make more sense when you’re working on a web app
– you can just deploy, and none of your users have to download or install the new version.

This flow works very well for us in our small 2-3 person iOS teams, and Scott says it works well
for them on their 15-20 person teams. If you’re not using feature branches in git – and just
committing everything to master – I’d highly recommend giving this approach a shot.

Become a master of iOS with our weekly newsletter where you’ll learn more about source
control, Cocoa Touch, Swift, and Objective-C – just drop your name and email in the boxes
below.
http://roadfiresoftware.com/2014/10/will-apple-reject-your-app-if-its-not-unique/

Will Apple reject your app if it’s not unique? 


Published by Josh Brown on October 7, 2014

If you’re building an app, you may be wondering whether it’ll be unique enough to make
it through Apple review process. This is an especially common question among people who have
never submitted an app to the App Store before. And it’s no wonder – the stories about apps
being rejected are circulated much more widely and loudly than the relatively boring, common
stories of apps being accepted.
So, will Apple reject your app if it’s not unique?
The short answer is no, probably not. As long as your app conforms to Apple’s App
Store Review Guidelines and doesn’t crash horribly, you have nothing to worry about.
Perhaps one of the bullets in the Introduction is troubling if you’ve never submitted an
app before:
If your App looks like it was cobbled together in a few days, or you’re trying to get your
first practice App into the store to impress your friends, please brace yourself for rejection. We
have lots of serious developers who don’t want their quality Apps to be surrounded by amateur
hour.
I know when that when I submitted my first app, I was afraid of getting rejected for this
very reason. I know I’m no designer, and I struggle to make things look nice when I’m
responsible for the design. I mean, just look at it:
It’s not pretty at all, it doesn’t do a lot, it’s not unique, and you might think it was cobbled
together in a few days. In reality, I only spent about a week building version 1.0 before
submitting it to Apple. And despite its relative lack of polish and pizzazz, they accepted it.

For another illustration, here’s the most recent app I built to sell on the App Store:

With this one, I took Sacha Grief’s advice about getting a side project from idea to launch in 10
hours. It’s just one screen, and when you tap that mail button, it brings up the built-in email
composer. And that’s all. I spent less than 10 hours on it. Remember what Apple said about that?

If your App looks like it was cobbled together in a few days…please brace yourself for rejection.

I was prepared for rejection on this one, since it was put together in less than a few days – but I
didn’t really expect it. I knew it was an app that would be useful to people, and that it was a
quality app. And I think that’s more important to Apple than whether you actually spent only a
few days on it. They want quality on the App Store, and honestly, I’d argue that they still let
some pretty low quality apps onto the App Store. Look at all the awful clones of popular apps
like Flappy Bird and Threes.

And that brings us to the question of uniqueness. Should you worry about your non-unique app
being rejected? Look at all the Flappy Bird clones, the Threes clones, the Kim Kardashian apps,
the hundreds of todo apps… If Apple approved all of those, why would they reject yours for not
being unique?
You have nothing to worry about. Read through the App Store Review Guidelines, follow
them, and build something useful. And chances are, your app will be approved.

Update: Check out Apple’s Common App Rejections for the most common reasons apps are
rejected.

If you’re ready to get your first app into the App Store, enter your name and email below to grab
my advice, tips, and tutorials on building iOS apps, and I’ll help you get there. And if you’re still
worried about whether your app will be rejected, shoot me an email after you join and I’ll let you
know what I think.
http://roadfiresoftware.com/2014/05/everything-you-need-to-know-about-xcode-objective-c-and-
ios-to-build-ios-apps/

Everything you need to know about Xcode,


Objective-C, and iOS to build iOS apps
Published by Josh Brown on May 13, 2014

So you know you should invest in learning Objective-C and iOS because it’s good for you – it’ll
allow you to invest in your knowledge portfolio, stay relevant, build and sell apps, take your
career in a different direction, and show off your work to your friends and family. But do you
know what specifically you need to learn? What parts of iOS and Objective-C are important?
What’s the quickest way to competence so you can move on to what you really want to do –
build your first app?

No matter how you choose to learn, you’re going to need to spend a lot of time with iOS and
Objective-C – there’s no getting around that. Additionally, you may want to invest money to get
you there more quickly. And whether you invest only time OR time + money, you want to make
sure you don’t waste it – you want to get a good return on your investment. So rather than
wasting your time learning some obscure iOS framework you’ll never use, focus on learning the
concepts listed below. These are the things you’ll use in almost any iOS app you develop.

You can use this list along your journey to check off what you learn. Or you can use it to evaluate
whether that course you found is worth the price – or just a waste of your hard-earned cash.

Xcode
Xcode is the IDE to use to develop iOS apps. It’s the only way to edit storyboards, xibs, and Core
Data files. Make sure that you’re working with the latest version – and that your course, book,
tutorial, or screencast is, too. If they’re teaching a different version from what you have, you may
have trouble following along. Apple is pretty quick about deprecating old versions of Xcode and
forcing developers to submit apps with the latest version, so don’t waste your time on an older
version.

Here’s what you should know about Xcode:

 how to create a new project, add files and classes


 how to build and run your app
 how to set breakpoints and debug
 how to browse and search Apple’s documentation

Objective-C
Objective-C, the language behind iOS, looks a bit strange to someone coming from other popular
languages like Ruby, Java, C#, JavaScript, and the like – largely due to its square brackets and
named parameters.
You should know about:

 the crazy syntax: square brackets, @ signs, pluses & minuses, and parentheses
 types
 Foundation objects
 classes: headers and implementation files
 defining, implementing, and calling methods
 how to use blocks

iOS
The iOS platform is what gives you access to all the great hardware in iOS devices as well as an
extensive library of user interface widgets. It defines lifecycles for applications and views that
you need to know, in addition to the basics like how to build a UI. Of course, you should be
learning on the latest version of iOS so you don’t waste your time learning the old UI,
frameworks, and classes.

Here’s what you should know about iOS:

 building a UI
 the application lifecycle (UIApplication, UIApplicationDelegate)
 the view lifecycle (UIViewController)
 navigation (navigation bar, tab bar, page control)
 table views (UITableView, UITableViewController)
 handling user interaction
 displaying and transitioning between views
 how to get data from a REST API (NSURLSession)
 parsing JSON (NSJSONSerialization)
 the latest version of iOS

If you want to learn all of this in one day…


…without the frustration of trying to read and process walls of text – you might like the iOS Boot
Camp. I’d love to have you, but I’m not going to pretend you don’t have other options. Just make
sure you don’t waste your time or money on something that’s not worthwhile.
http://roadfiresoftware.com/2014/11/how-do-you-distribute-beta-ios-apps-to-your-team/

How do you distribute beta iOS apps to your


team?
Published by Josh Brown on November 6, 2014

A few people have asked me recently how I distribute beta iOS apps to my team. The
short answer: Crashlytics Beta. It’s free, simple, and easy for my team to use.
Yes, I’m aware that Apple now owns TestFlight and that it’s also free to use. But did
you know that it only supports iOS 8 and above? So you’re not going to be able to have anyone
testing your app on iOS 7 through TestFlight. And even if you’re targeting iOS 8, TestFlight
may not be a good option.

Recently, a friend added me to his TestFlight team to test an app. But I never got the invitation.
He deleted me and added me again, but I still didn’t get the invitation. He even tried sending it to
another of my email addresses, and still, it didn’t work. We never did figure out why I didn’t get
those emails, but eventually we just gave up.

And in case you think this is an isolated issue, check out the App Store reviews of the TestFlight
app. This quote summarizes what I’ve heard from others:

So, I got it working, but there are multiple confusing steps. No way I’m trying to walk multiple
customers through this.

I’ve heard similar concerns from other developers who are trying to distribute their apps through
TestFlight. It doesn’t “just work,” things break without error messages, and therefore, it’s a waste
of time. So for now, I’ve settled on Crashlytics.

The one thing I don’t like about Crashlytics is the Mac app which, as far as I know, is required
for Beta distribution. It only runs in the menu bar and, so I can’t Alt-Tab to it, and the window
where I enter release notes and choose users is tiny…

When I get to the point where I’m annoyed enough with Crashlytics to warrant switching to a
new solution, I’ll take a good look at HockeyApp. It comes highly recommended by some of my
friends, and I like the fact that I’d be the customer, not the product.

If you’re looking for a way to distribute prerelease builds of your iOS app to your team, I’d
suggest staying away from TestFlight until Apple fixes some of the bugs and workflow issues.
For now, I’d recommend evaluating both Crashlytics and HockeyApp.

Don’t waste your time on broken tools…


Stay up to date on the latest and greatest iOS tools, third-party libraries, and development
practices by dropping your name and email in the boxes below.
http://roadfiresoftware.com/2014/10/what-third-party-libraries-do-you-use-for-ios-development/

What third-party libraries do you use for iOS


development?
Published by Josh Brown on October 14, 2014

I add new third-party libraries to my apps fairly conservatively, as I don’t want to depend on a
library where development may stop in the near future, leaving me without any support when I
have questions and issues with it. Here are the ones I use regularly – that I’m reasonably
confident will continue to be developed and supported for some time.

CocoaPods
Do you hate dragging and dropping libraries into your Xcode project? I sure do… I use
CocoaPods on every app I develop to solve that problem, as it makes adding other libraries so
much easier. CocoaPods also shows me which version of a given library I’m using and makes it
easy to upgrade to the latest and greatest (without requiring drag & drop).

Crashlytics
Crashlytics goes into every app I build, without question. It’s important to me to know about
crashes as soon as they happen, get a stack trace, and be able to track them down. Crashlytics is
free, easy to use, and the dashboard has nice features like the ability to add notes and mark
crashes as closed. Plus, they send me an email every time a crash happens. And as a bonus,
Crashlytics now has some basic analytics built in, so I don’t always need to include a separate
analytics tool.

AFNetworking / Alamofire
Nearly every app I build has a networking component, and for that, I like AFNetworking for
Objective-C, or Alamofire for Swift. NSURLSession is a decent API, and a huge improvement
over NSURLConnection, but AFNetworking/Alamofire just make networking so much simpler.
If you’re doing networking in iOS, you should be using one of these libraries.

Google Analytics, Mixpanel, or Localytics


Often, the apps I build need analytics to get a sense of how people are using them. If I were to
add analytics to an app now, I’d evaluate Google Analytics, Mixpanel, and Localytics. I’ve
always liked Google Analytics (and the fact that it’s free), but I haven’t evaluated Mixpanel yet,
and it’s been a while since I looked at Localytics. Flurry is definitely out – I’m maintaining an
app that uses Flurry for a client right now, and what I said about it earlier this year still applies –
the dashboard is still slow, clunky, and painful to use. It hasn’t had any noticeable improvements
in the last 8 months. On the other hand, Google Analytics continues to improve, and I know that
some people love Mixpanel.
Urban Airship
When adding push notifications to an app, I like Urban Airship. This was an eaiser decision back
when Urban Airship was free – now, they doesn’t even list their prices – you have to
“CONTACT SALES.” So when I’m building an app for myself or a small client, I probably
wouldn’t even consider Urban Airship any more – I’d evaluate Parse and Mixpanel instead,
whose prices look reasonable. But for larger clients who can handle the expense, Urban Airship is
a great solution.

New Relic
New Relic’s Mobile App Monitoring has been nice for tracking down performance issues while
the app is running in the wild. Their web dashboard provides a good breakdown of which parts of
the app are running slowly – it helped us to find out, for example, that Core Data will killing our
app’s responsiveness when it was running in our users’ hands.

ZBar
For 1D barcode scanning, I’ve settled on ZBar. When I evaluated all the barcode scanning
options in mid-2013, it came out on top, given the parameters. I was looking for something fast,
accurate, and reasonably priced, and it met all of those criteria. The paid options – RedLaser,
ShopSavvy, Scandit, Accusoft and VisionSmarts – sometimes scanned more quickly and more
accurately, but for us, those minor improvements weren’t worth the price. And ZXing, another
open source option, was fairly inaccurate and its documentation was sparse. If you’re adding 1D
barcode scanning to your app, consider ZBar as well as AVCaptureMetaDataOutput on iOS 7 and
above.

CorePlot
With one of my clients, we recently evaluated charting libraries, and CorePlot came out on top.
We wanted to like Jawbone’s JBChartView, but it just didn’t have what we needed. CorePlot
gives us the ability to create graphs where we can customize labels, axes, colors, and more as
well as tap on points.

Don’t waste your time doing things the hard way…


Stay up to date on the latest and greatest Cocoa Touch frameworks, third-party libraries, and
development practices by dropping your name and email in the boxes below.
http://roadfiresoftware.com/2014/08/a-safer-approach-to-json-parsing-in-swift/

A safer approach to JSON parsing in Swift


Published by Josh Brown on August 26, 2014

If you made it to the Beginning Swift workshop, you saw that we used valueForKeyPath: to
parse the JSON from iTunes like this:

var jsonError: NSError?


let json = NSJSONSerialization.J

if let unw rappedError = jsonErro

var jsonError: NSError?


1
let json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &jsonError) as
2
NSDictionary
3
 
4
if let unwrappedError = jsonError {
5
    println("json error: \(unwrappedError)")
6
} else {
7
    self.titles = json.valueForKeyPath("feed.entry.im:name.label") as [String]
8
}

And during the workshop, I mentioned that there are better ways to parse JSON. But what’s
wrong with the above approach? Well, it works just fine when we get the response we expect.
But what if we get a response we don’t expect?

The code above is missing all the type checks, which is what Swift does so well for us. It doesn’t
handle unexpected responses, since there’s no checking in valueForKeyPath – it just tries to grab
the value, and if it fails, it crashes. If, for example, the feed doesn’t contain the entry we expect,
our app will crash. Let’s look at handling this a better way using optional binding:

func titlesFromJSON(data: NSDa


var titles = [String]()
var jsonError: NSError?

1 func titlesFromJSON(data: NSData) -> [String] {

2     var titles = [String]()


    var jsonError: NSError?
3
    
4
    if let json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error:
5
&jsonError) as? NSDictionary {
6
        if let feed = json["feed"] as? NSDictionary {
7
            if let entries = feed["entry"] as? NSArray {
8
                for entry in entries {
9
                    if let name = entry["im:name"] as? NSDictionary {
10
                        if let label = name["label"] as? String {
11
                            titles.append(label)
12
                        }
13
                    }
14
                }
15
            }
16
        }
17
    } else {
18
        if let unwrappedError = jsonError {
19
            println("json error: \(unwrappedError)")
20
        }
21
    }
22
    
23
    return titles
24
}

So this time, when we parse our JSON, we’re using the if let syntax to bind new constants to
our optionals. And we’re checking the types on each to ensure that we have the data we expected.
Let’s start with the first if let statement:

if let json = NSJSONSerialization


// this code is executed if the
} else {
// otherw ise, this code is exe
if let json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &jsonError)
1
as? NSDictionary {
2
    // this code is executed if the json is a NSDictionary
3
} else {
4
    // otherwise, this code is executed
5
}

So in the first line, we’re turning our JSON into an object and checking to see whether it’s a
NSDictionary (with as? NSDictionary). If it’s a NSDictionary, the if block is executed, and
we can then use the json constant inside the if block. If it’s not a NSDictionary, the else block is
executed.

This optional binding continues through the code, though I’ve left out the else blocks for the
other if let statements for brevity. You could certainly include else blocks after each if let if
you wanted to do more extensive error handling.

The source code for this project is on GitHub – you can check out the JSONParser class, and see
both the titlesFromJSON (the better, safer approach) and compare that to the bad-json branch –
which uses the more dangerous approach.

There are tons of articles on parsing JSON in Swift out there, and there are certainly better ways
to do it than what I’ve done here. If you’d like to read some of the other articles, here are a few:

Parsing JSON in Swift by Chris Eidhof

JSON Parsing Reborn by David Owens II

Functional Wish Fulfillment by Rob Napier

Happy JSON parsing!

Don’t miss out on learning Swift before it becomes the way to write iOS apps. Stay ahead of the
curve with my weekly newsletter – just drop your name and email in the boxes below, and be
prepared to become a better Swift developer.
http://chris.eidhof.nl/posts/json-parsing-in-swift.html

Parsing JSON in Swift


Safe and easy
After reading Brent's and David's posts on parsing JSON in Swift, I really wanted to write this
post. However, we've been very busy with writing a book on Functional Programming in Swift,
and I wanted to finish some other things first, so it took a while to come up with it. The full code
accompanying this post is on GitHub.

In this posts I will give an outline of a parsing library for dealing with JSON in Swift in a type-
safe way. I bluntly copied the example JSON from David, and it looks like this:

var json : [String: AnyObject] = [


"stat": "ok",
"blogs": [
"blog": [
[
"id" : 73,
"name" : "Bloxus test",
"needspassword" : true,
"url" : "http://remote.bloxus.com/"
],
[
"id" : 74,
"name" : "Manila Test",
"needspassword" : false,
"url" : "http://flickrtest1.userland.com/"
]
]
]
]

Now, the challenge is to convert this into an array of Swift structs:

struct Blog {
let id: Int
let name: String
let needsPassword : Bool
let url: NSURL
}

I'll first show the finished parsing functions, which contains two operators: >>= and <*>. They
might look very foreign, but parsing the entire JSON structure is as simple as this. The rest of the
article only describes library code. The parsing below works in such a way, that if the JSON is
invalid (e.g. the name is missing, or id is not an integer) the entire result will be nil. There's no
need for reflection or KVO, we just have a couple of simple functions and some smart ways to
combine them:

func parseBlog(blog: AnyObject) -> Blog? {


return asDict(blog) >>= {
mkBlog <*> int($0,"id")
<*> string($0,"name")
<*> bool($0,"needspassword")
<*> (string($0, "url") >>= toURL)
}
}

let parsed : [Blog]? = dictionary(json, "blogs") >>= {


array($0, "blog") >>= {
join($0.map(parseBlog))
}
}

So, what does the above code do? Let's go over the most important functions. First, let's have a
look at the dictionary function. It's a function that, given a dictionary from String to
AnyObject, tries to find a dictionary with the specified key:

func dictionary(input: [String: AnyObject], key: String) -> [String:


AnyObject]? {
return input[key] >>= { $0 as? [String:AnyObject] }
}

For example, in the example JSON we expect the key "blogs" to contain a dictionary. If the
dictionary exists, the above function returns it, otherwise it returns nil. We can write similar
functions for arrays, strings, and integers (here are just their signatures, the full code is on
GitHub):

func array(input: [String:AnyObject], key: String) -> [AnyObject]?


func string(input: [String:AnyObject], key: String) -> String?
func int(input: [NSObject:AnyObject], key: String) -> Int?

Now, let's have a look at the outermost structure of our JSON. It is a dictionary, with a key
"blogs", which contains an array, under the key "blog". To parse that, we could have written the
following code:

if let blogsDict = dictionary(parsedJSON, "blogs") {


if let blogsArray = array(blogsDict, "blog") {
// Do something with the blogs array
}
}

Instead, we can define the >>= operator, which takes an optional value, and applies a function
only if the optional is not nil. It makes use of the flatten function, which flattens a nested
optional into a single one.

operator infix >>= {}


@infix func >>= <U,T>(optional : T?, f : T -> U?) -> U? {
return flatten(optional.map(f))
}

func flatten<A>(x: A??) -> A? {


if let y = x { return y }
return nil
}

The other operator that's in heavy use is the <*> operator. For the parsing of a single blog, we had
the following code:

mkBlog <*> int(dict,"id")


<*> string(dict,"name")
<*> bool(dict,"needspassword")
<*> (string(dict, "url") >>= toURL)

You can read this as a functional call that only gets executed when all optional values are non-nil:

mkBlog(int(dict,"id"), string(dict,"name"), bool(dict,"needspassword"),


(string(dict, "url") >>= toURL))

So let's look at the definition of the <*> operator. It combines two optional values: as the left
operand, it takes a function, and the right operand a parameter to that function. It checks if both
operands are non-nil, and then just applies the function.

operator infix <*> { associativity left precedence 150 }


func <*><A, B>(f: (A -> B)?, x: A?) -> B? {
if let f1 = f {
if let x1 = x {
return f1(x1)
}
}
return nil
}

Now you might wonder what mkBlog does. It is a curried function that wraps our initializer. First,
we create a function with type (Int,String,Bool,NSURL) -> Blog. Then, the curry function
turns that into Int -> String -> Bool -> NSURL -> Blog:

let mkBlog = curry {id, name, needsPassword, url in


Blog(id: id, name: name, needsPassword: needsPassword, url: url)
}

This is needed so that we can use mkBlog together with the <*> operator. If we look at the first
line:

// mkBlog : Int -> String -> Bool -> NSURL -> Blog
// int(dict,"id") : Int?
let step1 = mkBlog <*> int(dict,"id")

We can see that combining them with <*> gives us a new function of type (String -> Bool ->
NSURL -> Blog)?. And if we combine that with a string:

let step2 = step1 <*> string(dict,"name")

We get a function of type (Bool -> NSURL -> Blog)?. And if we continue doing this, we end
up with an optional Blog? value.

I hope you can now understand how all the pieces fit together. By creating a few helper functions
and operators, we can make strongly-typed JSON parsing really easy. Instead of optional, we
could have also used a different type that would include errors, but that's a topic for a different
blog post.

In our book, we'll be writing in much more detail about these kinds of things (and other really
cool stuff). If you're interested, you can already get early access today: Functional Programming
in Swift.
http://owensd.io/2014/06/21/json-parsing-take-two.html

JSON Parsing Reborn


If you read my previous piece on JSON Parsing in Swift, things looked really drab. And in fact, if
you try to use Swift straight-up to do it, it still sucks. However, while trying to make this
experience better, I stumbled across one very interesting feature of Swift that helped me create a
very light-weight JSON library that gives me all of the expressiveness I had with ObjC while
keeping true to the semantics of Swift.

In ObjC, we are able to express JSON as a literal construct made up of the various Foundation
types. There was a land-mine waiting if you didn’t use the right types, such as NSData, with
properly encoding them first, but it was possible to do and the syntax was great. In Swift, a
semantic JSON blob might look like this:

1 var json = [
2 "stat": "ok",
3 "blogs": [
4 "blog": [
5 [
6 "id" : 73,
7 "name" : "Bloxus test",
8 "needspassword" : true,
9 "url" : "http://remote.bloxus.com/"
10 ],
11 [
12 "id" : 74,
13 "name" : "Manila Test",
14 "needspassword" : false,
15 "url" : "http://flickrtest1.userland.com/"
16 ]
17 ]
18 ]
19 ]

That is semantically what we want and Swift will happily allow us to shove that into an
NSDictionary or Dictionary<String, AnyObject>. My fear was that creating a “real” version
of this in Swift would require manually boxing the types, and that sucks! And then I stumbled
upon a truly awesome feature of Swift. Seriously, it’s sweet!

Introducing Convertibles
Convertibles allow you to specify ways to convert most of the literals into a different type by
implementing a protocol. Let’s take a look at an example:

1 class MyDoubleDouble : FloatLiteralConvertible {


2 var double : Double
3
4 init(_ value: Double) {
5 double = value * 2
6 }
7
8 class func convertFromFloatLiteral(value: Double) -> MyDoubleDouble {
return MyDoubleDouble(value)
9
}
10
}
11
12
let double = 2.0 // double has a value of 2.0
13
let myDouble : MyDoubleDouble = 2.0 // myDouble.double has a value of
14
4.0

Ok. Things just got really interesting now. We can extend this to nearly all of the literal types,
including dictionaries and arrays. So we can actually keep the terse and expressive syntax from
above if we simply annotate the type for the JSON value:

1 var json : JSON = [ ... ]

With that one type annotation of JSON (defined in my library), that code gets created in a fully
type-safe JSON structure. That is pure gold.

Indexing the Goods


Retrieving the data from within the JSON is just as easy as well. If we overload the subscript
methods for strings and integers, we can provide full dictionary and array lookups that are type-
safe and conform to the semantics of Swift’s optional typing.

A quick example of grabbing the blog ID from the first blog in the structure.

1 if let blogId = json["blogs"]?["blog"]?[0]?["id"]?.number {


2 println("blog ID: \(blogID)")
3}

In The End
With just a little bit of work (and a lot of time fighting with current bugs in Xcode and Swift),
Swift makes it possible to toe the line between type-safety and expressiveness. I can only
imagine, that when we get proper documentation for all of this goodness, that most of my static
typing concerns will simply dissapear.

Feeling much more bullish on Swift today. =)

Full Source for the JSON project is here: https://github.com/owensd/json-swift/.

Вам также может понравиться