UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

How to reach the elements of that model and print their values?

Forums > Swift

Hey guys, I am trying to reach the elements of type Person that I did add to house1 of type House. But when I print it all I get is:

[test.Person, test.Person, test.Person]

I did not even use word test, apart of the fact that I run it in command line tool app that ive createn inxcode and named the file Test.

What am I doing wrong? Thanks!

import Foundation

protocol Resident {}

class Person: Resident {
    let name: String
    let age: Int

    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
}

class House {
    var residents: [Resident]

    init(residents: [Resident]) {
        self.residents = residents
    }

    func add(_ resident: Resident) {
        residents.append(resident)
    }
}

let person1 = Person(name: "Karol", age: 25)

var house1 = House(residents: [person1])
house1.add(person1)
house1.add(person1)

print(house1.residents)

2      

This is correct behavior, unless your class has CustomStringConvertible protocol implemented (I think it is this one), the output will be the bundle name and the class name when printing.

In this case, I would use something like a ListFormatter and gave it the names. It will do the rest :-)

https://www.hackingwithswift.com/example-code/system/how-to-join-an-array-of-strings-in-a-natural-way

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.