Swift scripting in OS X: Swift Encounters in Unexpected Places

Since the release of Swift, I’ve been looking for any excuse to do some work in Swift. My regular work does not afford me as much opportunity as I have hope. Months after the announcement and release of Swift, I still consider myself a noob. Recently, I have landed a gig with a client who develops in-house iOS apps with their Enterprise account but they are still very entrenched into Objective-C. It didn’t looked like I have the opportunity to advance my adventure in Swift; that is until I was looking at their certificate situation. Suffice to say, it’s in a mess. I’m tasked to straighten it out so to avoid the situation where suddenly apps stop working due expired certificate and the inevitable scramble to create app bundle signed with new certificates follow by the frantic release to the users.

I’ve started to unpack the IPA files to verify the apps bundles are signed with the correct certs and fix the bundles that are signed by an older cert that’s about to expire. Furthermore, I need to verify every new bundle before releasing to the users. I realized quickly that I would be doing the same thing often enough to be annoying but not enough to form the muscle-memory for remembering the commands and it’s flag to be effortless.

The verification task involves unzipping the IPAs to get to the contents of the app package, using the codesign tool to get the certificate name, and decrypt the provisioning profile within the app bundle to get the signing provisioning profile info. All of the commands I need to complete the task are command line tools, so I burst into my usual mode of solving such problem, which is to write a bash script. Midway through, I ask myself why do I need to write the parser to convert provisioning profile format (a property list) to a usable key-value pairing. That’s when I realized I should write a Swift script to do the conversion from plist to an NSDictionary for easy extracting of the values. This is the perfect excuse to dip into some Swift time.

The point to all this is to say there are many opportunities to hone one’s skill and where they come from may surprise you.

Now if you are still here for the after show (the real show), let’s go into some nerdy stuff.

Ultimately the bash script was still necessary because there are some things that are much easier done with a shell script than a language like Swift. Besides, I don’t want to spend time to reverse engineer codesign, and the decrypting tool, which are provided by Apple and readily installed, on my Mac. By combining the best part of shell script with the best part of a language like Swift, I finish a primitive (read fragile) set of two script is a relatively short amount of time.

Behold, the “provisioninfo” Swift script:

The only function of the Swift script is reading the provisioning profile in the form of an unencrypted plist from the stdin, convert to NSDictionary, and print out elements that are of interest.

The first line would look very familiar to those that are like me that have a background in shell scripting. The proper name for the line is shebang. If you are not familiar, it’s just the mechanism in Unix shell (bash in this case) to tell the shell how to execute the rest of the file. When the shell executes the script, the shebang line would not be passed into xcrun, therefore will not cause a syntax error.

If still unsure, just know that it is the very line that allows a Swift script be executed on the command line just like any compiled executable. That and of course with the file mode executable bit turned on as above.

The second strange looking line is a sign that the person who wrote the script is an emacs user. It’s a line that would inform emacs which editing mode to use when the file is loaded. It is normally not necessary if the filename includes the “.swift” extension but when I write scripts, I don’t like to have the extension included so visually, it’s the same with any executable. The problem is when there’s no filename extension, emacs could not figure out the file type and hence would not be able to auto-load the editing mode associated with the file type (having to manually set the editing mode, BAD!). In comes the file variable line. Normally, this file variable would be on the first line of the file but the shebang really need to be on the first line or the shell will not be able to pick it up. Fortunately, emacs is smart enough to pick it up even if the file variable line is located on the second.

Lastly, here’s the bash script that ties the whole operation together (note it’s shebang):

As I’ve said, both the script was written with minimal effort and a little fragile. I’ve probably made a few mistakes or did not use a better way to perform the task. Regardless, it’s a short but yet quality Swift time I’ve just spent. I’m satisfied with my day.

—Swiftloc signing off.

Objective-C as a Native Language

In the Debug podcast episode 42: Swift roundtable, the panel consisting of Natalia Berdys, Don Melton, Brent Simmons, Guy English, and Rene Ritchie gather to give us an interesting discussion around Swift and related topics in the Apple world. What strikes my fancy is that, one of the panelist, Natalia Berdys’ love for Objective-C and going so far as to calling Objective-C her native programming language. Interestingly, I’ve just a few weeks ago when I wrote the About page for Swiftloc, I too thought of Objective-C as my mother-tongue. I’d never thought anyone other than myself would refer to a programming language as native. Even though my concept of a native programming language does not mean the first programming language one would learn, I think we are on the same page in terms of our love for Objective-C.

Apart form the brief talk about Objective-C as one’s love, the episode is pack-full with Swift goodies. It’s a great discussion I wish I had the chance to partake because through out listening to the episode, I keep finding myself trying to butt-in to add my two cents even though all my butting-in is only happening in my head.

If you are here reading this, I can be fairly certain you are into learning Swift as well. So, if you are not familiar with the Debug podcast, episode 42 is a good place to start and if you aware (or already a subscriber) of the Debug podcast, make sure you don’t miss episode 42.


—Swiftloc signing off.

Swift Will Transform Computer Programming

Cade Metz:

Typically, when a new language appears like this—out of nowhere—it needs years to reach a mass audience. This is true even if it’s backed by a tech giant the size of Apple. Google unveiled a language called Go in 2009, and though it was designed by some of the biggest names in the history of software design—Ken Thompson and Rob Pike—it’s still struggling to gain a major following among the world’s coders. But Swift is a different animal. When it’s officially released this fall, it could achieve mass adoption with unprecedented speed, surpassing even the uptake of Sun Microsystems’ Java programming language and Microsoft’s C# in the late 1990s and early 2000s.

Cade wrote in his article for Wired exploring the reason Apple’s Swift language will instantly remake computer programming. I can’t say I disagree with any part of the article. I honestly can’t. In my 25 odd years of programming (professionally and as a hobby during my teenage years), I’ve never seen any single language that quite took the world by storm.

Here is my own observation and reason I agree with Cade:

  • Apple is well known for its ability to push new technology forward even though at times, with its users kicking and screaming. I don’t see an exception with the Swift language.
  • There are lots of vested interest from iOS/Mac developers to keep up with Apple’s development tools and offerings. When Apple deprecates Objective-C as a programming language for iOS/Mac, developers have to either pick up Swift or cease doing business on Apple’s platform.
  • Swift presents a lower barrier to entry for new comers compared to Objective-C. Being able to fiddle with life code and see the result instantly in Playground makes learning to program so much easier and fun.
  • If the reaction from developers during the WWDC ’14 unveiling of Swift is any indication, the uptake will surely be swift (pardon the pun).

Another point to note is that the tone used in Cade’s article looks like it is targeting a geeky reader base but not necessary with a background in programming. Maybe I have not been paying attention to the tech publication, but when was the last time you have come across an article that covers a programming language with the intended reader base of non-programmers.

—Swiftloc signing off.

PragPub Magazine on Swift

The current issue of the PragPub Magazine is heavily focus on Swift. From what I’ve been told, their purchasing handling server was so overwhelmed that some of the emails to notify readers of the download links was not sent out. It seems this is one of the most popular issue they’ve published.

It’s $1.99 for a single issue or $19.99 for a one-year subscription. If you are interested in Swift, I recommend you at least get the current issue.

The PragPub Magazine is available on iTunes or directly via The Prose Garden.

—Swiftloc signing off.

The Developer’s Dystopian or Utopian Future

Marco Arment:

Ed Finkler:
I find myself more and more concerned about my future as a developer. …

My tolerance for learning curves grows smaller every day. New technologies, once exciting for the sake of newness, now seem like hassles. I’m less and less tolerant of hokey marketing filled with superlatives. I value stability and clarity.

… I feel the same way, and it’s one of the reasons I’ve lost almost all interest in being a web developer. …

After reading Marco’s post The Developer’s Dystopian Future and subsequently Ed’s post of the same title , which Marco linked, I find myself thinking about the same topic. At 45, my age lands me squarely into the aging programmer group, even more so than Marco.

There is certainly something to be said about age and it’s inverse correlation with ability to learn new things. After all, the saying “you can’t teach old dog new tricks” was not plucked from thin air. However, at my age, I’m actually excited at learning Swift. Just that my motivation is not because of the newness of Swift but more because I find that Swift is the way forward if one is to keep doing development work on the iOS platform. It is also a chance to pick up some of the more current paradigm in modern programming languages that I’ve wanted to pick up for a while but had no opportunity until now. But most of all, I have always been passionate about programming and keeping up with the times is part of the passion.

There is some reluctance of course but it’s not the urge to resist learning something new. I feel it’s a little too early for me to move away from Objective-C. I have just started to learn Objective-C two years ago and I have yet to venture as deep into Objective-C as I like. I’ve mentioned in the About page that Objective-C feels like my mother-tongue even though I’m relatively new to Objective-C and there is uncertainty as to whether Swift will be as natural to me as Objective-C. In other words, I’ve not had enough fun programming in Objective-C. Note that none of these reasons have anything to do with my age.

Having said that, I do wonder from time to time if I’m too old for this shit. The constantly chasing the next programming trend can be tiresome at times. The fear of getting too old to be still valuable in the field is real. I am by no means trying to put down Marco or Ed about their feeling of age and seeing themselves somehow becoming less valuable in the field. Just that I find the thing that keeps me going is the passion to write code and to solve programming problems.

Marco Arment:

Swift looks interesting, but in all of Overcast’s development so far, I’ve never run into a problem that’s the language’s fault that Swift would have handled better. It appears to solve problems I don’t have, to gain small (and still theoretical) optimizations that I don’t need, at the expense of many Objective-C features I really like.

Beyond reflecting about my age and my future as a developer, there is one point I don’t agree with Marco. Marco pointed out that while developing in Objective-C for Overcast, he has not ran into problems that are the language’s fault. I don’t think any problems in any program written in any language can really be fairly attributed to the language’s fault. Language features are designed to support the paradigm behind the language design. Some languages are said to have a mixed paradigm, and features of the language are designed to support more than one paradigm. If a paradigm is applied using a language that is designed with the same paradigm, it usually mean the code is easier to write and clearer to read for other programmers. Usually. However, any paradigm can be applied to any language regardless if the language is designed for said paradigm. An extreme example would be writing code with the Object Orientated paradigm in Assembly Language (Don’t laugh. Have a look at this book: Object-Oriented Assembly Language). No doubt, without language feature to support a given paradigm, it will be difficult to write code using said paradigm but it’s not unachievable. But if a paradigm is applied with a language that is not designed with the same paradigm and things goes wrong, it is no fault of the language. The problem lies most definitely with the programmer.

In other words (or TL;DR in Internet speak), Swift is a different language that is designed with a different paradigm. In Apple’s own words, Swift is Objective-C without the baggage of C. So,  before you start learning Swift, you need to check your C baggage at the door.

—Swiftloc signing off.

The Swift Blog (official)

Apple has just launched the official Swift blog. This is far remove from the normal Apple we know and if memory serves, it’s the first blog officially Apple’s. Aside from the shock commentary, I don’t think the Swift blog will be a good resource to learn Swift but it would be a good channel to keep up with the development of the Swift language and it’s official. Regardless, it is a new blog and a little bare now. As of this writing, there’s only a couple of post, one about Swift Compatibility and the launch welcome post. Not to say that the Swiftloc is currently packed full with articles and valuable information, we’ll just have to wait to see where Apple’s newfound openness will lead us.

The Swiftloc Swift Resource page had been updated to include the official Swift blog.

—Swiftloc signing off.

Going Back to the Basic

It’s been roughly a months since Apple released Swift. I’ve made some headway in learning the language but I still feel that I have not made as much progress as I like. So far, reading documentation is not much help. What I’ve got from the reading is a concept here and an idea there but nothing ties together completely.

The experience has got me thinking.

As far as I can remember, I’ve always learned by example. I’ve never been able to learn well by academic style learning. What I mean is that I don’t learn well reading books, manuals, reference materials, and etc. It is also not that I don’t read those materials but I cannot just read them and absorb enough information to be useful. To me learning a programming language by reading a book about the language is as useful as learning a foreign language by reading a phrase book. It may help you order a mean and maybe find a toilet but you won’t be able to convey complex idea. Most definitely, you won’t be able to write a poem (or the equivalent idea of a poem) in a language you’ve learned from a phrase book. Although programming language books are more akin to grammar books but in terms of me actually learning the language, it feels more like a phrase book.

In my experience, the most effective way to learn a new programming language is to start a project. Have in mind what app you want to build and start by learning how to build it every step of the way. I find that if I have a clear start and finish and an objective to go with it, I am better motivated and retention is many times better. Objective is also a good mechanism to help focus the attention. It may take you down the path of random jumping from topic to topic but I can see a clear path to the end. Of course, it is not always permissible to learn in this manner. It may be due to work environment, or schedule, or many other reasons. Regardless, learning by building a project is still the best option to take if that is an option open to you.

Now, I just need to come up with an idea for an app…

If there is an app you want to see written in Swift? Head on below to tap on the contact link to get me to write it in Swift.

—Swiftloc signing off.

Swift Playground

A big part of why Swift is an attractive language is Playground. When I first saw Playground during WWDC’s unveiling of Swift, the immediate thought that cross my mind is that Playground is exactly how I program. What I mean is that when I am working on a project and I am not sure how to do a certain task, I would create a new test project to work out ideas or just general exploration to find a way to accomplish what I need to do in code. Sometimes, the solution don’t just arrive after one test project. There’ll be a second, third, and sometimes, many more. Iterate and iterate until I find the solution.

The procedure is such that I create a new project in Xcode. After which, I’d want to say start writing code and on the way to discover the ultimate solution to my problem. However, in reality, this is the point I’ll have to write the view controller, the views and what ever I need to bring it to the point I can start writing test code to even begin testing my ideas. In that way I’ve created and deleted countless test projects. Sometimes, the idea I’m testing requires fewer overhead code to support, while other times, I need to have an extensive setup that takes much longer than I’d like to even get to the point to start write test code.

With Swift and Playground, there are no need to write in complete programs. It’s like Apple was reading my mind when they got the idea to make Playground part of the Xcode suite to go with Swift. It is exactly how I’d write programs but with all the extra overhead taken out. In Apple’s own words:

Experiment with Swift code in an interactive environment known as a playground. Without requiring you to compile and run a complete project, a playground provides quick feedback for the results of your coding experiments. — Apple’s Documentation

I would have describe Playground a godsend!

Granted, you do need to have some setup code if you are trying to test something within something complex like figure out the path of an object in your game scene but all the support code will be in one way or another be directly related to what you are trying to test.

The other reason I brought up playground here is the fact that playground is the perfect tool for learning Swift. You can easily follow along a Swift programming book or an online tutorial on Swift you happen to find. Traditionally, programming books and tutorials are written in such a way that the central subject is precede with supporting code so that the example code presented is a complete program where readers could plug into the IDE for execution. Those supporting code can sometimes be way ahead the central topic at the given point of the text and very confusing for the readers to follow. Most authors would try to quickly brush over them either without much explanation or by writing “don’t worry about this part of the code for now.” I strongly feel that those overhead cruft gets in the way of learning the central topic. Now, with playground, I won’t say it’ll totally get rid of the cruft but at least keep it down to a minimum. I can’t wait to see how playground will transform teaching materials in the coming months.

—Swiftloc signing off.

Variable Basics in Swift

When learning any new programming languages, the first thing to learn is always variables. Well, apart from the customary complete program called “Hello World!” It show you how to write a complete program but teaches you almost absolutely nothing. Variables on the other hand is the cornerstone of programming languages. Without variables, programs that are of any use will be a hell to write. So, with that, let’s have a look at variables in Swift.

Note: The view I carry in relation to syntax of a language is from the traditional programming languages or more accurately languages that have it’s roots in the C programming language. That’s my frame of reference and what I’ve been writing in for most of my career.

At first glance

The variable declaration and assignment syntax seem so strange for someone coming from the more traditional compile language background. The pattern is always <constant modifier> [type] [variable name] <=[value]>[EOL delimiter] . Below is how you declare variables and constants Objective-C.

In Swift  var means variables and let  is constants. The pattern in Swift is reversed as compared to C++ [variable|constant] [name] <: [type] [= [value]]<EOL delimiter> . One of the immediately noticeable difference is that type is optional and if defined, it’s placed after the variable name instead of before.

If you compare the description in the comments between the two language, it is like Swift moved the definition of the declaration statement from code to your brain. There are more to think about when reading code in Swift because you need to infer the same things the compiler does and does so effortlessly. Needless to say, there’ll be some getting use to. Placing the type after the name is not going to help either.

The optional type rule

The rule to when the can be omitted is that it is optional unless the type cannot be inferred. If we program with that mode of thinking, a lot of tokens in the traditional programming language variable declaration is redundant. There are argument to be made if you like or dislike having to infer the type when reading code but there’s also something to be said about the brevity of the Swift syntax. On one hand, I like the concise syntax even though it means I’ll have to get use to inferring the type whenever I read Swift code. On the other hand, I hope it will not become a common practice for Swift programmers to start prefixing or suffixing type to variable names. If you are learning Swift today, please don’t.

Type is optional but spaces are not

Apparently spacing is an important part of the Swift syntax and in a very different way compared to languages like C/C++/Objective-C. For example:

It does not seem like it is a big issue on the surface because Xcode will catch it as you type and if you don’t use Xcode, the compiler will surely throws an error. I can definitely see how it will constantly interrupt my flow of thought to nitpick over code format. It will be a great source of little annoyance and it is not helpful to productivity. I do hope this is a problem with the Swift compiler not being completely ready for Swift than it is a formal language definition. It is quite useless to take so much obstacle out from traditional language programming and yet gives us some new obstacle. I’ll probably should find time to file a Radar for this one and I encourage everyone who is a Apple developer to do the same.

Uninitialize variables of a bygone era

There are no uninitialized variables in Swift. The compiler simply won’t let you leave variables uninitialized. Think about all those times your programs crash or have a strange and difficult bug to trace because of an uninitialized variable. Gone. No more. Not ever going to happened.

Type conversion

Conversion between different type must be explicit. I’m with the opinion that conversion explicitly is a good thing™. When the compiler of the language forces the programmer to be explicit in type conversion, a whole class of programming error simply evaporates. The trade-off is that the programmer have to write out the conversion regardless how obvious it may seem to the programmer. There is one exception to this rule however. The Swift allows a conversion shortcut within string literals, much like the Literals in Objective-C. I presume this exception is to allow string literals to be more readable.

Outside of a string literal, shorthand is not allowed but within string literal there are many useful things you can do within type conversions, for example computation. The rule of the conversion looks the same as the other traditional languages.

 Arrays and Dictionaries

There are not much to say about Arrays specifically as they are not much more difference between regular variables in Swift and other traditional languages. They are declared with brackets []  and access to elements is with the index within the brackets. Dictionaries are basically array that you can use indexes other than integers.

There is one syntactical note however. Trailing comma (,) is optional in a series of values and if present, will not cause an error.

If you have done any serious programming before, you would have use some source control management software like Git, Subversion, and etc. And if you have done any SCM related task, you will know that if you have an array or list that you need to expend the content at the end, the SCM software will always flag the previous last line as changed. So, in Swift, if you always have the trailing comma, all you need to do is add the new line and only the new line will be flag as add while no previous lines flagged as changed. It’s a very minor thing but a welcome touch to the Swift syntax.


All in all, I think there are a lot to get used to as someone with my background but the brevity of the syntax is positively welcome. The prevailing thing I’ve seen a lot of people talked about is that programmers who are well-versed in modern scripting language like Haskell, Ruby and the likes may find learning Swift easier. I will have no idea as I do not have any experience in those languages except the occasional glance either by accident or someone wrote something about them in an article I was reading online.

—Swiftloc signing off.

The Real “Hello World!”

Today I finally feel reasonably comfortable with the backend work done on the site. I’ve swept the last spec  of dust under the rug so to speak. I’m now ready to start writing. But before I dive into Swift, I want to take the opportunity to make a few notes of what have been going on in the backend.

I have look around and have consider a few choice and I went with WordPress for the blog. It’s a pretty robust CMS suit that focuses on blogging and have a very mature plugin and theme ecosystem. Resource can be easily found on the internet to do almost anything. With power and flexibility, it always comes with a cost and that usually mean the site may not keep up if there was an explosion of visitors (Of course there are ways to have a cache system in front of WordPress but I’ll cross that bridge when I get there). I did consider using a lighter engine like Pico (the CMS, not the text editor), however, they all feel like I have to put in a lot of work to even get started. If I had chose Pico, I would not have a beautiful Swift aware Syntax Highlighter working in such a short time.

Speaking of Syntax Highlighter, I came across Crayon Syntax Highlighter plugin. It would be really silly to ask the plugin author for a Swift parser when Swift is just 2 weeks old. So I took it upon myself to put in the language definition and color scheme that look like Apple’s own color scheme. The color scheme should make the Swift code on this site very familiar to those who read Apple’s documentation. Here is how it looks:

And that concludes my short note about the site. If you are eager to see real Swift content, the next post will be it. It’ll be published shortly (No, really. It’s being proof-read now…).

—Swiftloc signing off.