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:

[cc_swift width=”100%”] var myNickname = “trms” [/cc_swift]

In this case, we have assigned [cci lang=”swift”]myNickname[/cci] the string [cci lang=”swift”]trms[/cci]. Now whenever we refer to [cci lang=”swift”]myNickname[/cci] in code, we refer to [cci lang=”swift”]trms[/cci] until we change its value. We did not need to explicitely tell Swift that [cci lang=”swift”]trms[/cci] 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:

[cc_swift width=”100%”] var myWeight: Float = 12.34 [/cc_swift]

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:

[cc_swift width=”100%”] var greeting: String = “Hello there!” var myShoeSize: Int = 43 [/cc_swift]

Multi-line Strings

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

[cc_swift width=”100%”] let thisMultilineString = “”” I am a multiline string! Say wooo! “”” [/cc_swift]

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.

[cc_swift width=”100%”] let pi: Double = 3.14 var buttonPressed: Bool = false [/cc_swift]

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:

[cc_swift width=”100%”] 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” [/cc_swift]

Constants

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

[cc_swift width=”100%”] let tourEiffelHeight: Int = 1063 [/cc_swift]

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.

[cc_swift width=”100%”] let thisBeString: String = “OK” let thisBeInt: Int = 1 let thisBeBool: Bool = true [/cc_swift]

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 *