Subscribe now

More-Built_in-Types [11.09.2016]

Strings

Type this:

var aString:String = "Hello, playground"

This creates a string variable from a literal. Swift string literals are declared with double-quotes surrounding the content.

Swift strings support non-ASCII characters directly in literals, this is especially great if you prefer to develop in a language which uses lots of non-ASCII characters, or even emoji.

var aString:String = "Your card is the 3 of ♣."

Here's a String with a clubs character. That, it turns out, is pretty useful, even in English. Swift also supports many non-ASCII characters in variable names, like this:

var 🃓:String = "Your card is the 3 of ♣."

And don’t get me wrong, I love creating custom mathematical operators using the correct unicode symbol. But I spent more time searching through a unicode table to find the right character than if I had just typed out a name. Besides, some unicode characters are difficult to read. So I recommend that you only use non-ASCII characters where it greatly clarifies the purpose of the name, and its easy for the developer to read and type.

Strings can be concatenated just using the + or += operators.

var theirCard:String = "Your card is the" + " 3 " + "of "
    aString += "♣."

Here, we construct the string one piece at a time. But we can't append other types, like Int’s to String's:

var number:Int = 3
var aString:String = "Your card is the" + number +  "of "  //Error

But I think you'll find you don't want to do that much, because you can place an expression directly into the String literal:

var number:Int = 3
  var suit:String = "♣"
var aString:String = "Your card is the \(number) of \(suit)."

We put parentheses around a swift expression with a backslash before it. This is called String interpolation, and it looks similar to escaping. It is mostly useful in debugging.

Arrays

Now, let's survey collections in Swift. We'll start with Arrays.

Try this:

var integers : [Int] = []

It's an Array of integers. The type of the element goes inside the square brackets, and the empty square brackets initialize an empty array. Yes, even the collections are type-safe in Swift! If you’re moving from Objective-C or JavaScript, you’re going to love type-safe arrays. The type of the elements can be as precise or as lose as you want. Maybe what we really needed is an array of booleans:

var booleans : [Bool] = []

And, if we really do need to put anything in there, we can,

var anyGoes : [Any]

But the truth is, that’s not terribly useful, because there aren’t any functions that can operate on an Any, besides explicitly testing what type it really is. What we should do is pick a type which specifically provides the properties and functions we’ll need when accessing the elements in the array, even if that type is a protocol, which we’ll cover later.

An array can be randomly accessed by index, which must be an Int.

var integers : [Int] = [0,1,2,3]
var index:Int = 3
var anInteger:Int = integers[index]

The index goes in square brackets, called a subscript, similar to C-based languages.

Swift also includes the very popular for-in syntax.

for anInteger in integers {
  print("here's \(anInteger)")
}

The compiler inferred the type of anInteger based on the type of the array of integers. We'll talk about powerful functional programming methods like map and filter in another lesson.

Dictionaries

Let's create a dictionary,

A Dictionary is Swift’s name for a C++ map or a JavaScript associative array.

var dictOfStrings: [ String : Int ] = [:]

Just like declaring an array with square brackets and the value type names, so a dictionary is declared with the type name of its keys, followed by a : and then the type name the values. Here, We’ve created an empty dictionary of String keys which map to Int values. By including the : in the empty dictionary, we’ve distinguished it from an empty array.

So let’s insert a value in the array:

dictOfStrings["some key"] = 5

And we can iterate over them:

for (aKey, aValue) in dictOfStrings {
print("\(aKey) == \(aValue)")
}

Optionals

But when we try to pull an exact value out, we have to account for the possibility that it is not in there:

var someValue:Int? = dictOfStrings["key"]

The ? turns the type into an Optional, which means there may or may not be a Int. This is where your ears should perk up, because the compiler is actually keeping track of whether the values are missing. The universal value which means there is no value is nil.

var someValue:Int? = nil

We can initialize an optional with nil. Or with a value.

var someValue:Int? = 8

For an integer optional, being nil, does not mean being 0.

var integerOptional:Int? = nil
integerOptional == 0  //false

A nil value for an Int? means there is no `Int`.

We’ll talk more about optional values later, but for now I want you to remember that it’s perfectly safe to discover that a value is missing from a Dictionary, but if we tried to access a value in an array which was out-of-bounds, the app would crash:

var value = integers[1000] // crashes at run-time!

Instead, we should always explicitly check the count property of an array before explicitly randomly accessing elements:

let arrayCount:Int = integers.count

Summary

Today we learned about Strings. How to create them, combine them and place other values in them. We learned about non-ASCII characters in literals and symbol names.

We learned about two types of collections: Arrays and Dictionarys, both of which are type-safe in Swift. We learned that Swift has a convention for representing the lack of a value, called an Optional.

Meaningful text, types and even the lack of a value? Now that's Swift!