Variables
#variables
Overview
Whenever possible, always prefer constants over variables. In this way, Apple will stop you from an error.
Variables
int = 1
double = 3.14
string = "Hello"
bool = True / False
Sample parts of the code
var greeting = "Hello, playground"
var => type
greeting => variable name
= => assign
"" => variable value. Since it has " marks on both sides, it is String
private var & private (set)
To give access to outside of the struct you should initialize it (init).
struct Person {
private var socialSecurityNumber: String
init(ssn: String) {
socialSecurityNumber = ssn
}
}
let sarah = Person(ssn: "555-55-5555")
Even if one of the properties is private and did not call from outside of the struct, you should initialize it.
struct Doctor {
var name: String
var location: String
private var currentPatient = "No one"
}
let drJones = Doctor(name: "Esther Jones", location: "Bristol")
/*
error:
'Doctor' initializer is inaccessible due to 'private' protection level
*/
struct Doctor {
var name: String
var location: String
private var currentPatient = "No one"
// initialization
init(name: String, location: String) {
self.name = name
self.location = location
}
}
let drJones = Doctor(name: "Esther Jones", location: "Bristol")
print(drJones)
/*
print:
Doctor(name: "Esther Jones", location: "Bristol", currentPatient: "No one")
*/
Videos
Sources
Sources
Videos
Articles / Documents
Last updated
Was this helpful?