This is day 1 out of 100 for 100 days of SwiftUI and day 2 for 100 days of code! I started the 100 days of SwiftUI with a friend so that we would be each others accountability buddy. These are my notes from the course.
You can find my projects and playgrounds for the 100 Days on my 100 Days of SwiftUI GitHub Repo.
Today's topics were:
- Variables and Constants
- Simple Data Types
Declare variables with
Variables only need to be declared once and the value can be changed just by using the name
var str = "Hello, playground" // -> Hello, playground str = "Goodbye" // -> Goodbye
Strings and integers
Swift is a type safe language, which means that each variable has a specific data type.
str is a String meaning it holds letters
A number for an age can be stored as an
Int type. If using large numbers in Swift, you can use an
_ as thousands separators and it will not mess up the number.
var age = 38 // this is an integer aka a type of Int var population = 8_000_000 // _ can be used as a thousands separator
Strings can be declared with double quotes, but by doing that then line breaks cannot be included. For multi-line strings, use triple double quotes,
var str1 = """ This goes over multiple lines """
If formatting across multiple lines, but it is not to be outputted that way, then use a
var str2 = """ This goes \ over multiple \ lines """
Doubles and Booleans
Doubles hold decimal numbers like
If declaring a variable with a fractional number (decimal number), then Swift will declare the variable with a
var pi = 3.14 // type = Double
Booleans hold either
var awesome = true // type = Boolean
String interpolation = the ability to put variables into strings
To do this:
var score = 85 var str = "Your score was \(score)" // Your score was 85
Used to set a value that never changes and is declared with
let taylor = "swift" // swift
Trying to change the value of a constant will cause an error.
If a variable is declared and the value is not changed, Xcode will produce a warning.
Swift can infer a type based on what the value assigned to the constant/variable is (type inference).
Sometimes this works, but sometimes being specific would be better or help document what you are expecting the type to be. This is done by
var name: type_name for a variable or
let name: type_name = value for a constant.
let album: String = "Reputation" let year: Int = 1989 let height: Double = 1.78 let taylorRocks: Bool = true
That's it for today! Thanks for reading!
Top comments (2)
Thanks Arash! Me too 😄