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).

Example from HWS
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.

Wrong Code
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

*/
Right code
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

Hacking With Swift / 100 days / 11 - How to limit access to internal data using access control

Sources

Sources

Videos

Articles / Documents

Last updated