Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // STRUCTS (Part I)
- // Struct with one "stored" property
- struct Sport {
- var name: String
- }
- var tennis = Sport(name: "Tennis")
- print(tennis.name)
- // tennis and name are variables, so they can be changed
- tennis.name = "Lawn Tennis"
- // COMPUTED PROPERTIES
- // New struct with two stored properties
- // and one computed property:
- // NB: Constants cannot be computed properties
- struct Sport2 {
- var name: String
- var isOlympicSport: Bool
- var olympicStatus: String {
- if isOlympicSport {
- return "\(name) is an Olympic sport"
- } else {
- return "\(name) is not an Olympic sport"
- }
- }
- }
- let taiChi = Sport2(name: "Tai Chi", isOlympicSport: false)
- taiChi.olympicStatus // "Tai Chi is not an Olympic sport"
- // PROPERTY OBSERVERS
- // willSet{}: Used before a property is changed
- // didSet{}: Used after a property is changed
- struct Progress {
- var amount: Int {
- willSet {
- print("Progress is about to change.")
- }
- didSet {
- print("Progress is now \(amount) percent")
- }
- }
- }
- var progress = Progress(amount: 20)
- print(progress.amount) // "20"
- progress.amount = 40 // "Progress is about to change."
- // "Progress is now 40 percent"
- // METHODS
- // Functions inside Structs are called methods
- struct City {
- var population: Int
- func collectTaxes() -> Int {
- return population * 1000
- }
- }
- let smallCity = City(population: 10_000)
- print("We can collect \(smallCity.collectTaxes()) in taxes!")
- // MUTATING METHODS
- // Swift won't allow a struct's method to change it's associated properties,
- // unless the "mutating func" keywords are used
- struct Person {
- var name: String
- mutating func changeNameToFred() {
- name = "Fred"
- }
- }
- var jim = Person(name: "Jim")
- jim.changeNameToFred()
- jim.name // "Fred"
- // PROPERTIES AND METHODS OF STRINGS
- // Strings are structs!
- // And have their own properties and methods
- let string = "Do or do not, there is no try."
- // count property
- string.count
- // various methods:
- string.hasPrefix("Do") // return true
- string.uppercased() // everything now uppercased
- string.sorted() // returns array
- // PROPERTIES AND METHODS OF ARRAYS
- // Arrays aare also structs!
- // Yep, they've got their own properties and methods
- var beatles = ["John", "Paul", "George", "Ringo"]
- // count property
- beatles.count
- // add new item method
- beatles.append("Fifth Beatle")
- // locate item method
- beatles.firstIndex(of: "John")
- // sort method
- beatles.sorted()
- // remove item method
- beatles.remove(at: 0)
Advertisement
Add Comment
Please, Sign In to add comment