Yesterday, I started my journey of learning SwiftUI. Day 0 was a great intro on what’s to come, but the real work started today. During Day 1, I’ve learned about variables and constants, how to create regular and multi-line strings and about integers and doubles. Now that I’ve went to the first official day, I’m happy to share some of the highlights!
SwiftUI’s Variables & Constants
SwiftUI uses variables and constants to store data. These two types are not so dissimilar. They are both used to store various data that can be used throughout your program. Even the declaration looks similar. The key difference lies in the fact that the value of a variable can be altered, while that of a constant is set in stone, so to speak.
var myVariable = "This is a variable"
let myConstant = "This is a constant"
// This works, because a variable can be changed.
myVariable = "This variable is changed"
// This will throw an error, because it's a constant.
myConstant = "This constant is changed"
Strings, Integers and Doubles
SwiftUI uses a handful of datatypes. The one’s I’ve gone over today are strings, integers and doubles.
Strings contain text, and not much else. It can be a single word, a whole sentence or even a whole book. They are declared using a variable or constant and the text must be within double quotes. There are also multi-line strings, which you would use if you’d want to insert line breaks into your string. In that case, you’d start the string with three double quotes on a single line and end it with three double quotes on a single line as well.
Integers and doubles are both used for numbers. An integer is a whole number, while a double holds decimal numbers such as 0,1. Since Swift is a type-safe language, these can’t directly be mixed. If you want to learn more about that, check out Paul Hudson’s short article on the matter.
Besides storing the data, Swift also all sorts of functions built in based on the data type. These functions allow you to work with your data in various ways. For example, a string can be counted, or can be printed in all CAPS, while numbers can be added, subtracted, multiplied, etcetera.
let myFirstInt = 3
// This will add 3 to myFirstInt, making the new value 6.
myFirstInt += 3
let myFirstString = "Count"
// This would print the amount of character, which is 5.
There was more to the first day, of course. But these were the highlights. I’m off to a good start and I’m looking forward to tomorrow already. That’s it for today, I hope you enjoyed this short read and be sure to let me know what you think in the comments below!