Mar 19, 2017
287 Wyświetleń

Trying to make friends with Swift

I finally managed to upgrade my mac to Sierra and was able to install the new version of Xcode. Hip, hip, hooray! I can go on now with the next chapters of my favourite App Development with Swift :)

It’s worth to mention that the book is sometimes really funny:

And the author really knows what’s important in life ;)

But anyway, today I want to tell you about some of Swift’s features that I learned about and that are somehow different from what I am used to. I look at the language from my c# point of view, try to find similarities and make constant comparisons: How would I write this line of code in c#?

Here are some of my „Swift wonders”. Today it’s going to be mostly about formatting.

There’s no need to put a semicolon at the end of the instruction.

A newline is like a semicolon. With my pedantic attention to detail I just can’t leave this without a comment. It’s as if a statement would miss a period. I don’t like it ;) I found myself completely lost in programming languages that rely on whitespace formatting: like indents in Python. And talking about whitespace:

The += operator likes to hug ;)

I don’t really understand why, but the following assignment produces an error:

a += 5;

whereas these two are perfectly fine:


a+=5;
a = a +5;

It looks as if Xcode treats the space in += operator as a separator between the two statements. It even gives me a free hint encouraging to place a semicolon to fix the issue, which makes here no sense at all ;)

I’m used to whitespaces in c#, it makes the code more easy to read for me. I found the whitespace rules in Xcode somehow inconsistent. And since I’ve already mentioned operators:

Forget the ++ operator.

This is a surprise. The increment by one operator has been removed from the third version of Swift. Can’t really think of a good reason for doing this ;) I remember my first programming classes at school: the ++ operator was always present.

The brackets.

Windows or Linux? Android or iOS? Opening brace of a flow control in the same or in a new line? There have been flame wars on all of these. I choose Windows over Linux, iOS over Android and I do put opening brace in a new line. In my opinion it improves code comprehension. I have to find out if there is a way to make Xcode format braces in c# style ;) But as far as braces are concerned, the following lines of code


if (home_alone())
    turn_the_volume_up();

won’t compile in Swift but would in c#. Swift requires to put braces in if-statements even if the control flow consists only of one instruction. I think the main reason for this is to avoid errors like this:


if (home_alone())
    turn_the_volume_up();
    watch_some_porn();

The second function call after the if-statement is executed every time, but can be easily missed, because it is intended to the same level as the first one. This can lead to some serious consequences ;)