Don of the Day

Don of the Day


Adventures in software development with Xamarin and the Web

Software developer, building things with code in sunny Scottsdale, AZ.

Share


Twitter


Beginning Swift - The VERY Beginning

Don FitzsimmonsDon Fitzsimmons

Here we go. The learning process with most languages begins with learning about variables. Swift tutorials are no different. But, before I started learning about these fundamental concepts, I needed to be able to run code samples. If you're running a Mac, you can simply download Xcode and start a new "Playground". A Playground is a special project in Xcode designed for learning Swift. It's really just an advanced REPL and it's a great way to get your feet wet.

But, you may not have access to a Mac. There's still hope, dear reader. I found this great Swift REPL hosted by IBM. Not sure what the relationship is between Swift and IBM, but they have a sweet online Swift REPL that you can use anywhere a browser is available. It works like a Playground, it's just not as feature-rich. So, if you're without a Mac, you're still in luck if you want to learn Swift. Now that I had a place to run code, it was time to learn the ultimate beginner thing we do in software, the "hello world" program (my inner-grammar-Nazi want's to say, "hello, world" but who cares, he's super-inconsistent anyway).

Remember, I'm writing this blog series from a C# developer's perspective, so I'll be drawing parallels over the course of my experience learning Swift with C#. Also, with Javascript. Yep, Javascript too. Anyway, variables. Let's talk about those because they're a little bit unique in Swift. Below is the obligatory hello world program in swift:


print("Hello world!")

Now that's a buzzkill, right? How boring can a program be? But there's something interesting about this single-line program. There's no entry point. What the what? It's just a print statement. With C# and Java, we'd need something like this to enter a program:


class SomeClass
{
    static void Main(string[] args)
    {
        System.Console.WriteLine("Hello World!");
    }
}

Swift doesn't require a main method as the entry point to start executing code. It just magically executes it in-place. Now, I don't know all of the details behind this, but I do know that it's pretty unique and semi-interesting. Let's get to the variables by modifying our super-basic program.


let hello = "hello"
let world = "world"

print(hello, world)

//prints: hello world

What's with this let business? If you've seen any Javascript ES6 syntax, you might think you know what this means. You'd be wrong. And, frankly, that's confusing. Unlike ES6, let is not a block scoped variable, it's a constant. Yep, a constant. Once you set a constant in Swift using the let keyword, it can't be changed. And if you try to assign it again, the compiler will yell at you with a big red highlighted line. Nobody wants to be yelled at by a compiler. Declaring a type using a let, is like using the const keyword in C#. Set it once and don't try to set it again (unless you want to be yelled at by the compiler).

And here's a unique thing to Swift, they're all about using let over var. If your value doesn't change, Xcode is going to let you know. And really, it makes sense. How sloppy of us C# people to have variables all strewn out in our applications that are really just constants. Really, we shouldn't be making everything a variable. The Swift compiler gently suggests that your variables be constants if it detects that they don't actually change. That makes sense, right?

Back to the main point. There's something interesting about these two declarations though. Notice that? Swift is very much about type safety, but we didn't preface our constants with a type of String. Well, that's because the Swift compiler knows how to infer types based on the context in which they're assigned. Because we gave each declaration a String value, the compiler knows we intend for those declarations to be strings. Oh, yes, like Javascript, right? No. Not like Javascript. If you later try to assign an Int value to the hello constant, you'd get yelled at by the compiler again because Swift has determined that the constant hello is a String from the context it was assigned in.

Okay, but I need more than constants. I need variables that, you know, vary. Maybe it's hello now, but It could be "Hola" later. That's where the keyword var comes into play. Yep, if you write C# or Javascript, you're familiar with this one. In C#, much like Swift, var can preface a variable and based on the assignment, the type will be inferred from the type assigned. When using Swift, this is the preferred method of declaring variables, so I'm told. And frankly, that's also the case with C#. Here's an example:


var hello = "hello"
let world = "world"

print(hello, world)

hello = "Hola"

print(hello, world)
//prints hello world
//prints Hola world

There you have it. A type that varies. A variable. It's initialized with the var keyword and a value of "hello" and then changed to "Hola". Such sweet magic. The possibilities. But, what if you want to declare a variable or constant with a type specified. You'd use some funky looking syntax to do it. Funky looking, but I find that it really makes sense. See, in Swift, you declare the type after the variable name, separated by a colon. It looks weird, but makes sense from a human language point of view. See:


var hello: String = "hello" 
let world: String = "world"

print(hello, world)

hello = "Hola"

print(hello, world)

See what I mean? It looks weird. But stop and think about it for a minute. Declaring the type after the variable name makes sense. It's like saying "variable hello is a string and equals hello." Contrast that with the same thing in C#:


String hello = "hello"; // yikes! semi-colons. Swift doesn't need these
const String world = "world"; 

Notice that this doesn't read (from a human perspective) as nicely as the the Swift example. I mean, the C# way is much more familiar, but when you really think about it, it's a bit awkward to say "a variable of type string called hello equals hello." There's no poetry there. Nope. None. Anyway, C# bias aside, I think Swift gets this little detail right. And you don't need to use semicolons in Swift. You shouldn't use them at all (that's a lot of saved keystrokes).

There you have it. You can use a free online REPL to run Swift code (no need for a Mac at first). If you do have a Mac, you're in good shape and can use Xcode Playgrounds to, well, play with Swift. Also, Swift doesn't require a Main method in a class to execute code. I have no idea how that works, but it's cool. And, now you know that let is a constant, var is a variable and that we have type inference. If we want, we can declare the type of a variable or constant up front using some sexy syntax. We also found that you don't need to end every line with a semicolon. But, what happens when you run into this, and you will quite often run into this piece of strangeness using Swift (often):


var hello: String? //WTF is that question mark doing there?
let world: String = "world"

hello = "hello"

print(hello!, world) // does this mean, "really loud HELLO"?
//prints hello world // but why? WHAT'S HAPPENING?

To find out what all that ?!?!? crap is about, you'll have to wait until my next post about "optionals". Until then:


print("Goodbye, world!")
//prints "Goodbye, world!" -- but you knew that already, because you're almost as clever as me ;)

Software developer, building things with code in sunny Scottsdale, AZ.

Comments