Structures, Methods and Properties
struct Town{
**//Properties**
let name = "Maxland"
var citizens = ["Max", "Tom Brady"]
var resources = ["Grain" : 100, "Ore": 42, "Wool": 75]
//**Methods** or in essence what the object can do
func fortify(){
print("Defenses Incresed!")
}
}
Here is the object that we can now use to access the properties
//this is an object
var myTown = Town()
//prints the citizens from Town
print(myTown.citizens)
//we can also modify it. This will now add Keanu Reeves no the Citizens
//for the myTown object
myTown.citizens.append("Keanu Reeves")
Used as blueprint
//blank properties for each attribute that can now be defined as custom property
struct Town {
let name: String
var citizens: [String]
var resources: [String: Int]
init(townName: String, people: [String], stats: [String: Int]){
name = townName
citizens = people
resources = stats
}
}
//object is created from the blueprint
var anotherTown = Town(townName: "Nameless Island", people: ["Tom Hanks"],
stats: ["Coconuts": 100])
//Can now tap into the properties of the object
anotherTown.citizens.append("Wilsin")
It’s a better practice to do it this way for init…
Using self refers to the Struct’s property and the entirety of the structure
init(name: String, citizens: [String], resources: [String: Int]){
self.name = name
self.citizens = citizens
self.resources = resources
}