Interesting Swift Features

Great post by Mike Ash on some of Swift's interesting features. His explanation of Optional Types is specially good.

The existence of NULL in C (which is the same as nil in Objective-C) means that all pointer types in the language are implicitly optional types. If you have a NSString *, it means "pointer to NSString, or nil". If you have a char *, it means "pointer to char, or NULL".

The existence of NULL in C blows apart the entire static type system when it comes to pointers. Every pointer type is a half truth. Whenever you see a type "pointer to X", there's always an implied "...or NULL."

Working with Reverse Ranges in Swift

Update: Xcode 6 beta 4 was released today and there are changes pertaining iterating through ranges. I'll update again once I've a chance to experiment with it.

Reverse ranges have a weird behaviour in Swift. For example:

for index in 5..<1 {
    println(index)
}

The code above results in an infinite loop. That's because the loop starts from 5 and increments at each iteration, never actually reaching 1.

In order to get the expected result of printing the numbers from 5 to 2, one should use the by() member function of the range structure, passing in -1 as the value for the step:

for index in (5..<1).by(-1) {
    println(index)
}

Note it’s necessary to enclose the range inside parentheses.

However, there’s a catch. Iterating in reverse through the open interval, built with ..<, will yield the expected behaviour, which in the example above is to print the values 5, 4, 3 and 2. However, if the closed range operator - ... - is used, instead of going until 1, the loop will stop at 3. Weird, but that’s because a...b is defined as a..<advance(b,1).

Another option to iterate through a reverse range is to use the ReverseRange() function, which will work as expected for closed ranges:

for index in ReverseRange(range:1...5) {
    println(index)
}

The code above prints 5, 4, 3, 2 and 1 as expected. However, the same code with an open range operator will print starting from 4, since the reverse of 1..<5 is actually 4...1.

Adapted from my answer on Stack Overflow

Making HTTP Requests in Swift

As I mentioned in a previous post, I've been meaning to write more about programming here. While my initial idea was to set up a separate feed, I'll just post as I normally do and think about it on another occasion.

I'll start with a series of posts on Swift, Apple's new programming language for iOS and OS X development. The first few posts will be based on some of my answers to questions on Stack Overflow. So, without further adue, let us discuss simple HTTP GET Requests in Swift.

The same options available in Objective-C can be used with Swift. I'll only cover those that don't involve using third party libraries such as AFNetworking.

Using NSURLSession

First, initialize an NSURL object and an NSURLSessionDataTask from NSURLSession. Then, run the task with resume().

let url = NSURL(string: "http://www.stackoverflow.com")

let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) in
    println(NSString(data: data, encoding: NSUTF8StringEncoding))
}

task.resume()

Pretty straightforward. Also, the block syntax in Swift is much more pleasant to read and write, specially when benefiting from trailing blocks, which is possible since the block parameter is the last argument to the NSURLSessionDataTask initializer.

Using NSURLConnection

First, initialize an NSURL and an NSURLRequest:

let url = NSURL(string: "http://www.stackoverflow.com")
let request = NSURLRequest(URL: url)

Then, you can load the request asynchronously with:

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
    println(NSString(data: data, encoding: NSUTF8StringEncoding))
}

Or you can initialize an NSURLConnection:

let connection = NSURLConnection(request: request, delegate:someObject, startImmediately: true)

Just make sure someObject implements the NSURLConnectionDataDelegate protocol, and then deal with the data received in the appropriate delegate methods.

For more detail, check the documentation for the NSURLConnectionDataDelegate protocol

Testing on an Xcode playground

In order to try this on an Xcode playground, add import XCPlayground to your playground, as well as the following call:

XCPSetExecutionShouldContinueIndefinitely()

This will allow you to use asynchronous code in playgrounds.

Final remarks

While I provided code that uses both NSURLSession and NSURLConnection, NSURLSession is the preferred solution. Even though NSURLConnection isn't officially deprecated, this has been stated by Apple engineers on several occasions during WWDC sessions.

Finally, here's a gist with the NSURLSession based implementation.

Adapted from my answer on Stack Overflow

On Swift

One of the least expected and most exciting announcements of this WWDC has been Swift - an all new programming language for iOS and OS X development.

There’s been a lot of praise on how Swift is a truly modern language with a friendly syntax, and how it will enable developers to be more productive.

However, as much as Swift is a big deal on the short term, you don’t change[1] a platform’s language just to make things nicer and developers more productive in the present. You do it because it will,in the long run, enable things that weren’t possible before, by allowing for a new way of thinking about problemas and how to solve them. But as nice as it may be, and for as much potential as it might have, a language is only as good as what it enables developers to accomplish. On that front, Swift is off to a very good start.

By being fully compatible with all the same Apple APIs and Frameworks as Objective-C, Swift has a major advantage out of the gate to guarantee its wide adoption. Add it to the fact that it will run on the most popular developer platforms that have ever been around and you get a sure formula for success. That’s precisely why comparisons to the Dylan effort of 20 years ago shouldn’t lead to the conclusion that Swift will have the same fate. The context is very different.

Even though Swift code can coexist peacefully with Objective-C inside the same project and with full interoperability between them, it is free from having to comply to ANSI C standards. It’s effectively free from C’s legacy and doesn’t need to follow conventions established in a context that is 40 years old and may no longer be relevant, necessary, or, generally applicable. This will free developers from dealing with a lot of cruft. Of course, the frameworks are still written in Objective-C, so it will take a long time before they’re able to take advantage of all of Swift’s new features and start being made primarily with Swift in mind.

Swift further confirms what is easily observable for anyone who has a clue about Apple. They’re in it for the long run. Swift’s development and its launch this week wasn’t meant to solve the problems of today. Objective-C wasn’t exactly holding Apple back right now, but it might, someday. While Objective-C and Next’s acquisition, along with Steve Jobs return, saved Apple in the end of the 90s, it’s Swift the programming language which will help power Apple’s future going forward. It will enable Apple to continue fostering innovation within its platforms for the decades to come, while providing an incredible platform for third parties to develop on.


  1. Objective-C isn’t going anywhere, at least in the near future, so Apple hasn’t really changed the language for its platforms. It has added a new possibility, but it’s pretty clear that going forward, Swift will gradually become their platforms’ main language, eventually replacing Objective-C for good. It’s where Apple’s attention is from now on, and where ours as developers should be too.  ↩

After WWDC

WWDC has ended, but the real work starts now. It seems Apple decided this was the year they'd make all of its platform's developers dreams come true. A massive amount of new APIs that not only allow existing apps to get even better, but that enable whole new categories of apps that previously were not possible. On top of that, there's Swift an all new programming language. As such, there's a lot of work to be done, in a good way.

Extensions will bring applications the ability to customise user experiences across iOS and OS X while at the same time collaborating with other apps. Continuity will allow apps to provide their users with the ability to seamlessly transition between devices, taking their current task from one context to another with ease. iCloud drive and document sharing features will bring great data sharing between apps without giving up on the sandboxing model that helps make iOS secure.

But all of this is just the beginning. These are things we've long asked for, and the first wave of improvements to existing apps and new apps will aim at using the new APIs to solve problems we've all had and wanted to tackle for a while. But there is a whole new class of opportunities most of us aren't even aware of right now. The great new apps of the coming years will come from those who see such opportunities and successfully execute on them.

If you've been developing for iOS for a while, but not long enough to have taken part on the early life of the App Store, you may feel you've missed the train. But with what has been announced this week, there are a lot of trains just about to leave their stations right now. There's plenty of time to hop on one of them and reap the benefits.

Loom is joining Dropbox

It’s been a long road and we feel that we have come a long way in solving this problem. We are elated to announce the next step in this journey: Loom is becoming a part of the Dropbox family. We look forward to this transition as the next step in creating a home for all of your photos and videos, seamlessly organized, while still keeping them at your fingertips. With Carousel, Dropbox has created a gallery for your life’s memories. It’s a single home for all your photos and videos, automatically organized and always with you.

A few months ago, I struggled with the choice between Loom and Picture Life. I am glad I picked the latter.

Considering Spotify over Rdio

Spotify finally officially arrived in Brazil[1], and along came a major redesign of the iOS and Mac apps, bringing the long awaited collection feature.

I had tried Spotify before using Unblock-Us, but I couldn’t sign up to the service with a Brazilian credit card. Anyway, having to organize my song collection through the exclusive use of playlists was a major deal breaker, and I had decided to stick to Rdio, even though the Spotify catalogue seemed better suited to my tastes, from my limited experience.

While Spotify’s collection feature is a great addition, which finally makes the service usable for me, it’s still inferior to Rdio’s implementation.

On the Mac, you can view a grid of artists, but once you choose a particular artist, all you get is a list of songs which are sorted by album. Rdio on the other hand offers the possibility to view a more compact list of artists on the side, while offering a grid view of an artist’s albums, which can be toggled to a list view of songs sorted by album.

On iOS, there is no grid view, but the same problems hold. Once you are viewing you album collection, there is no way to filter by artist. If you navigate to an artist, you can only see the list of songs by that artist. There’s no way to see a list of albums.

On the mac, I also find the album covers in the grid view too large. Using the Spotify app on full screen on my 13" Retina Macbook Pro, I can see 4 albums per row. Comparing that to iTunes, which shows 8 albums in a row I find it much easier to browse my collection on iTunes than on Spotify. While Rdio shows only 5 albums per row at most on my laptop screen, it’s not as much of a problem since there’s the ability to filter the album grid by artist, which is what is actually lacking in Spotify.

As a side note, I also enjoy Rdio’s lighter style over Spotify’s predominantly black design.

As to pricing, Spotify is currently cheaper, with its premium plan at $5.99 per month. Rdio’s unlimited plan is currently priced at $9.99 per month.

With all that said, even though I find the Rdio app superior, the choice of services is no longer a no brainer. Spotify’s new collection feature, while lacking in several aspects, is good enough to make me seriously consider it over Rdio. The defining factor is no longer the apps, but the catalogues offered by each service.


  1. The dreadful licensing issues continue to be present, limiting the experience for international users on Spotify, and all similar services. It’s one thing if an artist or label decides not to distribute its content through streaming services at all, or licenses exclusively to a single service. However, regional limitations for availability of specific pieces of content feel artificial and are poisonous to the TV, music and movies industry. It is an artifact of a time before content distribution had the means to be as ubiquitous at it is today. It has to go.  ↩

Xcode Plugins

Xcode has had a plugin architecture going back to when Interface Builder was its own separate app. However, this system was relatively obscure, undocumented, and not widely used by third parties. Despite this, developers like Delisa Mason and Marin Usalj have done incredible work creating a stable and vibrant ecosystem of third-party Xcode extensions.

Simply install Alcatraz, and pull down all of the plugins (and color schemes and templates) that you desire.

Nice list of Xcode add ons.

Don Melton's Memories of Steve Jobs

The room got quiet. Steve and I sat side-by-side in front of the demo machine staring at Safari. Suddenly we turned to each other and said at the same time, “In the page address field!”

 

Smiles all around. Which I followed with, “I’ll have a working version of that for you by the end of the week.” Over-committing my engineering team, of course.

But I didn’t care. I had just invented something with the Big Guy. True, it was a trifle, but there’s no feeling like sharing even a tiny byline with Steve.

Great, great read. Everything Don Melton writes online should be compulsory reading for every Apple fan. There aren't many sources around for this kind of material, much less with Melton's eloquence and ability to naturally convey his emotion.

Little Big Adventure Review

Touch Arcade has a review of Little Big Adventure, a classic PC game which has been ported to iOS and Android as of last week. The game is currently priced $3.99 both on iOS and Android.

Back in the late nineties, I played through and enjoyed thouroughly the game's sequel, Little Big Adventure 2: Twinsen's Odissey, without having ever played the first one.

Today, I finished the game on my iPad. As one would expect from any port of a title that is 20 years old and relied completely on the keyboard for input, not everything was perfect. On the other hand, it's far superior to most of the iOS "serious" gaming experiences I've had. As such, I take issue with a few parts of the review.

The aim of the game, and how to progress is also extremely unclear. Little Big Adventure is a game where you kind of find your own adventure, and how you opt to tackle obstacles. No arrows show you where to go, and there is no quest log. These are some aspects that would have needed some reworking to accommodate the demands of today´s gamer.

Little Big Adventure is not a casual game. The aim of the game or how to progress is not unclear. It's explained through dialogues with NPCs and interaction with elements of the world. Finding the next step is part of the game due to its highly exploratory nature. If it's difficult to discover what to do next, it's by design and not at all a flaw. It's actually refreshing to play a game that makes the player think, rather than handing instructions for every step on a silver plate.

I remember having direct control over Twinsen on my PC using arrow keys for movement. On iOS the movement is indirect with you touching where you want Twinsen to go. This would be a suitable control method if Twinsen had any intelligent way to avoid obstacles. If something is in the way he simply walks, or runs into it. When just exploring this is a minor annoyance, but as soon as you are trying to escape an enemy it almost breaks the game. It tears on patience though, and having to restart in the asylum being caught by the fascist elephant guards is truly testing my patience.

I'll concede that the controls are not ideal. But the port made a good job adapting them to what would be possible on a touchscreen - far better than slapping a virtual joystick with virtual buttons and calling it a day. Whether this is enough, is a matter of opinion.

Porting a classic isn’t all that easy to do, and sometimes it might be better to ponder remixing or at least remastering the original material. Little Big Adventure is a clear example of this where some core elements such as controls, lack of direction and confusion to when the game saves make it less than ideal for mobile gaming. Personally I really wanted to fall in love with Little Big Adventure again some twenty years after our first affair. Sadly it has aged even worse than me, and not even nostalgia can get me past that. It is a true shame, as beyond the problems there is a terrific genre defining adventure to be found.

What is ideal for mobile gaming? What is mobile gaming? Is it playing on a line while looking up every 10 seconds? Is every game that is adequate to a mobile platform necessarily a casual game?

I sure hope not. I enjoy playing Cut the Rope while waiting for coffee, but when I sit on the couch at home to play games on my iPad, I want as much of an immersive experience as a game like Little Big Adventure can offer. The nostalgia surely contributed to making this particular game so enjoyable. But I hope a mildly negative review as the one linked here won't stop gamers who never had the opportunity to accompany Twinsen on his adventures from enjoying this wonderful game.

Software writings

I've been considering writing more about my software development related explorations, much like Brent Simmons does in his own blog. The main difference (other than the fact it'll probably take a good while until I can reach Brent level quality) would be I'd do so on this website, but on a different page and feed.

I am not set on this. I'll give it some thought in the next few days.

One year

Almost one year ago, on April 20th, I wrote on this blog for the first time. Since then, I've posted 33 times, mostly linking to posts from other authors and adding a comment. While the number of posts, both links and original content, has been less than ideal, it's pretty much on par with what I expected from my first year.

I had wanted to write online for a long time before I finally started, and while I have yet to build an audience, the experience has been satisfying in a number of ways.

First, writing online forces me to not only have my own opinion about the subjects I'm interested in, but to stand by it. This made me a more thoughtful reader overall.

Second, I've obviously been practicing my writing more. Since I chose to write in English, it doesn't hurt that I brush up on my language skills either.

Third, and more importantly, it made me want to write more. It's often said that people who think they'd love to write, are generally just enamoured with the idea of writing. The only way to know if you'll like it is to actually do it consistently and see if you enjoy it.

While my writing here has been far from consistent, it has been enjoyable. As such, I'll stick to it, write more than ever, and see where it goes.

Can’t We All be Reasonable and Speak English?

Stack exchange recently launched Stack Overflow in Portuguese

From the blog post which explains the reasoning behind the new community:

Even if I believed that every programmer must eventually master English, it still wouldn’t make any sense to make them do it first. I believe that everyone – everyone – who can really fall in love with programming should get a chance to. So pre-filtering for the ones willing to learn a foreign freaking language before they first sit down with a code editor to see if it lights some spark in them just feels wrong. Think of the children.

There are many very solid points made in the post.

I am not a native English speaker, but my parents provided me with the opportunity to study English as a second language in a school which was probably the best available, albeit unexpensive. I worked hard to get to the level where I could write my own blog in English, and maybe even pass as a native speaker in situations where my accent won't be noticed.

From the comments on the Stack Exchange blog, many people seem to take issue with the point made in the article and with the value of having a Portuguese based community. Weirdly enough, many of them don't even express themselves in English that well, at least from the writing in their comments, which I am sure was very well thought through, as all of internet commenting always is.

I can understand how people from countries that speak English natively would see the problems with fragmenting the body of knowledge as more important than the pain felt by those who do not have access to the body of knowledge at all. But I find rather puzzling that people in a developing country such as Brazil would believe that the Brazilian community would be better off having only the English version of Stack Overflow to rely on, even when a large portion of said community can't read in English well, and most can't express themselves at all.

Face is not the Future

Ben Thompson on the Oculus acquisition by Facebook.

Setting aside implementation details for a moment, it’s difficult to think of a bigger contrast than a watch (or ring) and an Occulus headset that you, in the words of Zuckerberg, “put on in your home.” What makes mobile such a big deal relative to the PC is the fact it is with you everywhere. A virtual reality headset is actually a regression in which your computing experience is neatly segregated into something you do deliberately.

Apple Will Sell The iPhone In Brazil For Nearly $1,200

I am linking to Business Insider. Can't really believe it.

To put that in perspective, consider that the Brazilian average wage is about 2,000 reais per month, according to Trading Economics. On that measure, an iPhone costs the equivalent of more than a month's wages. Brazil's income stats fluctuate more widely and frequently than those of the U.S. The World Bank recently put average income per capita (a different measure of wealth) at just over 9,000 reais. The U.S. equivalent is about $47,000.

This seems accurate. The prices we usually pay for electronic devices is ridiculous. When it comes to the iPhone and other Smartphones, our carrier subsidies are nowhere as strong as those in the US. Those of us privileged enough to buy an iPhone regardless of its abusive pricing here, usually have the option to buy them abroad for a lower price.

So why would Apple charge more than the U.S. for a phone in a country that is poorer?

One part of this is that Apple is not actually trying to be the most popular phone company. It is trying to be the richest phone company: Apple takes 87% of all mobile phone profits in the entire world, according to analyst Tavis McCourt at Raymond James.

Now, this, has nothing to do with the iPhone pricing in Brazil in particular. This is how Apple prices their products regardless of the market they are in: at a premium level, because they are premium products. The particularly high prices in Brazil are much more related to how abusive our tax policy is. This is not an iPhone only situation.

2013 Stack Overflow User Survey Results

Last year, as usual, I participated on the Stack Overflow User Survey and now the results are out.

Some of the interesting observations:

Working Remotely

As our Stack Exchange team is growing and we have more employees working remote, we added a number of questions about remote work. While only 10.6% of respondents said they are full-time remote, 63.9% of total respondents say they work remotely at least occasionally.

I am very glad to be among the 10% who answered they worked remotely full-time. It took me over a year to get to this, and I love every bit of it.

Android continues to climb while iPhone declines

Not only is the Android Phone the most popular mobile device with 63.8% of respondents saying they have one, the most popular native mobile platform supported is an Android Phone app with 39.5%. The iPhone lost more traction with developers this year with 30.7% of respondents saying they own an iPhone compared to 35.2% in 2012.

There is no such thing as The Android Phone. There are many phones which are, each of them, an Android phone. I don't find this observation nearly as meaningful as suggested.

Finally, out of the top 11 most used languages last year, Ruby ranked last, just below Node.js, with only 9.8% of respondants stating they had used it. Objective-C ranked as 9th. I would have expected Ruby to have a higher rank, at least definetelly above Objective-C and Node.js.

My mom's iPad

I got my first computer in 1997, when I was 9.

In the years that followed, that PC and the ones that came after it became central to my life. I used a computer for all the regular stuff such as schoolwork, games and IM, as well as learning to play songs on my guitar and tinkering with web design. I later got my first Mac, got serious about programming and started making a career out of it.

Through a significant portion of my childhood and all of my teenage years, I spent countless hours in front of a computer (probably, a lot more than was healthy, which, combined with my intense guitar playing, got me a mild case of RSI by the time I was 17). For a long time, one person wasn’t very happy with this state of affairs: my mother.

My mom didn’t understand computers. More than that, she didn’t like them, or, in her words, she hated them. She repeatedly said she didn’t want to learn to use computers. She really didn’t want anything to do with them. Specially, she didn’t like the fact that I spent so much time using them.

Very slowly, she started to give in. Some of her friends started getting e-mail accounts, and eventually she decided she wanted one. For a while, she still would ask me or my dad to check it for her and type her messages. Then, I taught her how to use instant messaging, she started browsing for news, did some audio and video chat on Skype and got into Orkut (it used to be pretty popular in Brazil) and later, Facebook.

At this point, my mom was actually proud of what she could accomplish. So much so that I convinced her to stop typing all in caps by telling her that people who read it would think she wasn’t good with computers. I had been in college for a while, and she had the computer all for herself most of the time. Even when I was home, I’d use exclusively my MacBook. However, there was still the occasional problem. She still needed help with mail attachments, she didn’t manage files at all (most of her stuff was kept inside the same folder) and crappy Windows alerts would still freak her out from time to time. Also, introducing any new activity for her to do on the computer took a lot of getting used to: adding favourites for easy access, teaching how to navigate the often cluttered web pages and many other hassles. This was a slow process, which slowly took place through the course of almost 15 years.

Then, in 2011, I got an iPad 2.

I bought it for myself. But I barely used it. I showed it to my mother and she fell in love instantly. Needless to say, I had to go mostly without an iPad until I bought a new one. [1]

Fast forward to today, my mom uses the iPad for everything she previously used the PC for, and a lot more. She watches Brazilian soap operas on the web. She plays the occasional card game. She watches movies on Netflix and iTunes, which she figured out all on her own how to browse the catalogues and how to add subtitles to non Brazilian movies. More importantly, she enjoys herself a lot more. There is no frustration, no insecurity (“should I click Yes or Cancel?”). She is willing to experiment more and discovers something new regularly. It didn’t take her 10 years to get used to the iPad.

Yesterday, I introduced her to Duolingo. I created her an account, walked her through a lesson and handed her the iPad back. She is now learning English. She actually cheered when she completed her second lesson in a row, with no mistakes.

Pretty magical, indeed.[2]


  1. I recently bought an Apple TV, which almost suffered the same fate.  ↩

  2. I got inspired to write this after reading this beautiful piece by Shawn Blanc. You should definitely give it a read.  ↩

The Stratechery 2013 Year In Review

Stratechery launched on March 25, 2013 with the post Welcome to Stratechery. While I had somewhat prepopulated the blog with old content (including a piece on the original iPad and a research paper on Apple and the Innovator’s Dilemma), the vast majority of my 203 posts and linked-list items came after that date. Here’s a quick summary of the highlights:

If you by any chance haven't been reading stratēchery for the whole of 2013, make 2014 the year you start doing so. Even though Ben Thompson defines it as a hobby, his writing is packed with deep and thoughtful analysis that rises above the noise in the echo chamber. After all, one can be pretty serious about his hobbies, and this surely seems to be the case.