Introduction to Swift

Apr 24 2024 · Swift 5.10, iOS 17, Xcode 15

Lesson 03: Classes & Structures

Class & Struct Demo

Episode complete

Play next episode

Next

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

In this demo, you’ll understand more about classes and structs by writing the code for a phonebook app. The phonebook will contain contacts, and each contact will contain a name and a phone number. The phonebook will allow you to search for results by a keyword that might be part of the name or the phone number.

struct Contact {
  var name: String
  var phone: String
}
struct PhoneBook {
  var storedContacts: [Contact] = []

  func save(contact: Contact) {

  }

  func search(keyword: String) -> [Contact] {
    return []
  }
}
class PhoneBook {
func save(contact: Contact) {
  storedContacts.append(contact)
}
  private var storedContacts: [Contact] = []
func search(keyword: String) -> [Contact] {
  var results: [Contact] = []  //1

  for contact in storedContacts {  //2
    if contact.name.contains(keyword) ||
        contact.phone.contains(keyword) {
      results.append(contact)
    }
  }

  return results //3
}
let phoneBookInstance = PhoneBook()
let ehabContact = Contact(name: "Ehab Amer", phone: "0123456789")
init(name: String, phone: String) {
  self.name = name
  self.phone = phone
}
phoneBookInstance.save(contact: ehabContact)
phoneBookInstance.storedContacts.append(ehabContact)
let samePhoneBook = phoneBookInstance
let kodecoContact = Contact(name: "Kodeco", phone: "0112233445")
samePhoneBook.save(contact: kodecoContact)
dump(samePhoneBook.search(keyword: "01"))
dump(phoneBookInstance.search(keyword: "o"))
var kodecoContactCopy = kodecoContact
kodecoContactCopy.name = "Kodeco Copy"

print(kodecoContact.name)
print(kodecoContactCopy.name)
See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Memory