objc

Hashtag Swift

I recently started developing for iOS using Swift. I did a little project creating a simple tic tac toe app nearly a year ago. Written in Objective-C obviously, because Swift hasn’t been around back then. I remember being stunned by the weirdness the language had to offer; especially coming from a php and javascript background. Let me give you a little example:

https://gist.github.com/1448a92686ee40cb7db6

For people that do not know Objective-C let me guide you through this a litte. This is the implementation of a class method named getFieldTextAtRow:andCol:. It takes to Integers (row and col) and returns an NSString. In the return statement the class method getFieldAtRow:andCol: is called passing the two variables into it. It then asks for the .text property of the returned object. Wow. Calling Methods on an object requires some strange square bracket syntax. Accessing parameters on the other hand is just a plain simple Object.parameter. A dash defines a method. A simple String is a NSString (which is written as @"String") and method name and parameters are entangled. I could go on… but, lets not ramble about dem ol’ days too much: Along comes Swift.

Swift is an innovative new programming language for Cocoa and Cocoa Touch. Writing code is interactive and fun, the syntax is concise yet expressive, and apps run lightning-fast.

Let’s look at the example Method again – this time written in Swift:

https://gist.github.com/d61634ebbf747715e0cd

A String is a string; A method is defined with a func keyword and a method is called just like a function. The name of the method is just getFieldText. Because of backwards compatibility (I guess) parameter names are still in the call. Exception to the rule is the first parameter. Objective-C had it inside the first part of the method name, so Swift “needs” to do that too. func getFieldTextForRow(row: Int, col: Int) -> String would be called like getFieldTextForRow(13, col: 37). The hash symbol in front of the first parameter tells the compiler, that you do want to explicitly name it. So basically that number sign makes stuff more consistent and a little less awkward. I tend to use it all the time.

After all Swift lets you do very cool stuff and in some aspects it is miles ahead of other languages. But some of the “I-need-to-support-all-the-weirdness-of-my-grumpy-father”-aspects just leave me scratching my head.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>