Day 1 – Simple Data Types

The 100 days start with twelve days of very basic concepts, an introduction to the language so to speak. Despite me having already covered these topics in the past by myself, it can’t hurt to review them again.

Variables

In Swift, we declare a variable and assign it a value like so:

var myNickname = "trms"

In this case, we have assigned myNickname the string trms. Now whenever we refer to myNickname in code, we refer to trms until we change its value. We did not need to explicitely tell Swift that trms is a string, as it is able to infer a value’s type from its content. We do need to be careful however when assigning numerical values, as Swift cannot tell the difference between, say, a Double and a Float and we need to instead specify it like so:

var myWeight: Float = 12.34

Variables should only be used for values which are expected to change during runtime. For everything else, we should use constants.

Strings and Integers

Strings are sequences of characters, while integers are, essentially, round numbers. We declare them like so:

var greeting: String = "Hello there!"
var myShoeSize: Int = 43

Multi-line Strings

This is how we create multi-line strings in Swift:

let thisMultilineString = """
I am a multiline
string! Say wooo!
"
""

We need to pay careful attention to make sure the quotes are in their own line.

Doubles and Booleans

Quite simply, Doubles are types holding decimal values, while Booleans are either true or false.

let pi: Double = 3.14
var buttonPressed: Bool = false

String Interpolation

Here’s something I particularly like becaue of its intuitiveness. You can take any value, of any type,1 and put it in a string like so:

var beanCount = 2
let beanExplanation = "The number of beans in the box is \(beanCount)"
print (beanExplanation) //output: "The number of beans in this box is 2"

Constants

I’ve been using constants throughout this day anyway, but here’s how you declare one:

let tourEiffelHeight: Int = 1063

Type Annotations

I’ve also used type annotations throughout the day. Essentially it’s when we specify exactly what type we want a value to be, without relying on the internal type inference system thingie.

let thisBeString: String = "OK"
let thisBeInt: Int = 1
let thisBeBool: Bool = true

This about wraps it up for today.


  1. that I know of so far

Leave a Reply

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