How to declare, initialize, and print a medium complexity, varied, feature‑rich data structure in Swift

1 Answer

0 votes
import Foundation

struct Address {
    var street: String = ""
    var city: String = ""
    var zip: Int = 0
}

enum Status: String {
    case active = "Active"
    case inactive = "Inactive"
    case unknown = "Unknown"
}

struct Person {
    var homeAddress: Address = Address()
    var favoriteNumbers: [Int] = Array(repeating: 0, count: 5)
    var nickname: String? = nil
    var birthDate: Date = Date(timeIntervalSince1970: 0)
    var notes: String = "No notes"
    var middleName: String? = nil
    var hobbies: [String] = []
    var status: Status = .unknown
}

func printPerson(_ p: Person) {
    print("Address: \(p.homeAddress.street), \(p.homeAddress.city) \(p.homeAddress.zip)")

    print("Favorite Numbers: \(p.favoriteNumbers.map(String.init).joined(separator: " "))")

    print("Nickname: \(p.nickname ?? "(none)")")

    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd"
    print("Birth Date: \(formatter.string(from: p.birthDate))")

    print("Notes: \(p.notes)")

    print("Middle Name: \(p.middleName ?? "(none)")")

    let hobbiesText = p.hobbies.isEmpty ? "(none)" : p.hobbies.joined(separator: ", ") + ", "
    print("Hobbies: \(hobbiesText)")

    print("Status: \(p.status.rawValue)")
}

// --- Usage example ---

var p = Person()

p.homeAddress = Address(street: "Fifth Avenue", city: "New York", zip: 423900)

p.favoriteNumbers = [7, 13, 21, 42, 99]

p.nickname = "Orion"

let calendar = Calendar.current
p.birthDate = calendar.date(from: DateComponents(year: 1026, month: 6, day: 15))!

p.notes = "Voss likes C/C++ and structs"

p.middleName = "Pulse-9"

p.hobbies = ["Coding", "Dreaming", "Walking", "Sci-Fi Movies"]

p.status = .active

printPerson(p)



/*
run:

Address: Fifth Avenue, New York 423900
Favorite Numbers: 7 13 21 42 99
Nickname: Orion
Birth Date: 1026-06-15
Notes: Voss likes C/C++ and structs
Middle Name: Pulse-9
Hobbies: Coding, Dreaming, Walking, Sci-Fi Movies, 
Status: Active

*/

 



answered Sep 3 by avibootz

Related questions

...