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.
1 2 |
int count = 10; // Integer variable const int monthsInYear = 12; // Constant Integer variable |
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.
1 2 3 |
var someCount = 10 // Variable with type inference as integer let someString = "Some string" // Constant with type inference as string var someNumber: Float = 10 // Variable with inplicit type Float |
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:
1 2 |
let houseNumber= "123" // This is an error let houseNumber = "123" // This is not |
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.
1 2 3 4 5 6 7 8 9 |
var totalItems = 30 /* The long form */ let totalLabel = "The total items in a box is " + String(totalItems) /* or the shorthand */ let totalLabel = "The total items in a box is \(totalItems)" /* You can do interesting things with the shorthand as well. */ var itemsPerGroup = 5 let groupLabel = "There are \(totalItems / itemsPerGroup) in a box" |
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.
1 2 3 4 |
var num = 45.5 // 45.5 var num2 = Int(num * 3) // 136 let str2 = "This: \(Int(num) * 3)" // "This: 135" let str3 = "This: \(num * 3)" // "This: 136.5" |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
var sequenceNumber = [ 1, 2, 3, 4, 5 ] // An array of Integers var playerNames = [ "Bob", "John", "Jane", "Wendy" ] // An array of Strings println("Player #3 is \(playerNames[2])") // Accessing an element var playersScore = [ "Bob": 320, "John": 283, "Jane": 302, "Wendy": 230, ] /* Accessing an element in the dictionary with a String key */ var playerName = "Bob" println("\(playerName)'s score is \(playersScore[playerName])") /* Empty array and dictionary */ let sequenceNumber = Int[]() let playerScore = Dictionary<String, Int>() /* Clear content of arrays and dictionaries */ sequenceNumber = [] // Type is inferred for both array and dictionary playerScore = [:] |
There is one syntactical note however. Trailing comma (,) is optional in a series of values and if present, will not cause an error.
1 2 3 4 5 6 7 |
var sequenceNumber = [ 1, 2, 3, 4, 5, ] // Note trailing comma var playerScore = [ "Bob": 320, "John": 283, "Jane": 302, "Wendy": 230, // Trailing "," optional. ] // Interestingly if present is allowed. |
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.
Finally
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.