Member-only story
Swift language
After to written a lot of post about SwiftUI on my persona blog i decided to create a blog about only SwiftUI, just to create a learning path.
In this i’ll show the fundamentals of the Swift language.
Let’s start with the simpler things, comments, variables and constants:
// It's a line comment
/*
This is a multiline
comment
*/
// Variable definition:
// var varname: Type = Initial value
var name: String = "Nicola"
The variables are defined using the “var” keyword, a name, after the “:” we must write the type of the variable (String, Double, Float, Array, Set,..)
The variable can be also declared shortly, omitting the type and setting directly the value, in this case, the variable gets the type of the value.
// declaring an int variable omitting the type
var age: 10 // age is an integer
The constants are declared in the same way, apart from using the “let” keyword and that they can get only a value that can be changed.
let pi = 3.14
pi = 4 // Error can't change costant value
In Swift we can declare a variable as optional, the variable can assume every value of the type defined and the “null” value. In this way, the nulla value became a possible value for that variable. An optional variable is defined appending the “?” to the type:
var myOpt: Int?
myOpt = 3
// to get the myOpt value
if let value = myOpt {
print("Value \(value)")
} else {…