Object-Oriented Programming: Beyond the Basics

Oct 17 2023 · Swift 5.9, iOS 17, Xcode 15

Lesson 02: Polishing Object-Oriented Programming Concepts

Demo 1

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, your going to write some logic to determine whether a contact is a person or a company. The first thing to do is introduce the ability to mark a contact as a company. Open the starter Playground. It’s been refactored into separate files. Expand the navigator by clicking the Hide/Show navigator button. Expand the Sources folder, then open the ContactCard.swift file. Add this new field to the ContactCard definition:

public class ContactCard {
  let contactID: UUID
  var firstName: String
  var lastName: String
  var phoneNumber: String
  var relatedContacts: [UUID]
  public var isCompany: Bool // new code
  ...
public init(firstName: String, lastName: String, phoneNumber: String) {
  self.firstName = firstName
  self.lastName = lastName
  self.phoneNumber = phoneNumber
  contactID = UUID()
  relatedContacts = []
  isCompany = false // new code
}
let kodeco = ContactCard(firstName: "Kodeco", lastName: "", phoneNumber: "1111111111")
kodeco.isCompany = true

let razeware = ContactCard(firstName: "Razeware", lastName: "", phoneNumber: "1111111111")
razeware.isCompany = true

print(kodeco.contactInformation())
print(razeware.contactInformation())
//print("Ehab contact contains Tim contact: \(containsTim)")
//print("Tim contact contains Ehab contact: \(containsEhab)")
kodeco.addRelatedContact(razeware)
kodeco.addRelatedContact(ehabContact)
print(ehabContact.contactInformation())
public func addRelatedContact(_ contact: ContactCard) {
  relatedContacts.append(contact.contactID)

    if isCompany == true && contact.isCompany == true {
      print("Both this contact and the new contact are companies. Adding 2-way relationship")
      contact.relatedContacts.append(contactID)
    } else if isCompany == false && contact.isCompany == false {
      print("Both this contact and the new contact are people. Adding 2-way relationship")
      contact.relatedContacts.append(contactID)
    }
}
public func addRelatedContact(_ contact: ContactCard) {
  relatedContacts.append(contact.contactID)

  if isCompany == contact.isCompany {
    print("Both this contact and the new contact are the same type. Adding 2-way relationship")
    contact.relatedContacts.append(contactID)
  }
}
See forum comments
Cinema mode Download course materials from Github
Previous: Instruction 1 Next: Instruction 2