Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listing all class attributes swift 3

I'm trying to print all the values from an object that inherits from a class, here is my example:

I create the class:

 class Pokemon {

 var name: String?
 var type: String?
 var level: Int?
 var exp = 0.0
}

Create the object and assign some values:

var pikachu = Pokemon()

pikachu.name = "Pika Pika"
pikachu.level = 1
pikachu.type = "electricity"
pikachu.exp = 0

Now I would like to loop through all the pikachu object attributes and print the values. I'm thinking in a for each loop but I'm not sure how to implement it.

I know I can do something like this:

func printStats(pokemon: Pokemon) {

if pokemon.name != nil {

    print(" name: \(pokemon.name!)\n level:\(pokemon.level!)\n type:\(pokemon.type!)\n exp: \(pokemon.exp!)")

 }
}

printStats(pokemon: pikachu)

output:

name: Pika Pika
level:1
type:electricity
exp: 0.0

But I just want to loop through all values, instead of explicit writing every attribute in the function.

like image 223
extrablade Avatar asked Nov 16 '25 23:11

extrablade


2 Answers

I found it the way of doing it:

let pokeMirror = Mirror(reflecting: pikachu)
let properties = pokeMirror.children

for property in properties {

  print("\(property.label!) = \(property.value)")

}

output:

name = Optional("Pika Pika")
type = Optional("electricity")
level = Optional(1)
exp = Optional(0.0)

and if you want to remove the "Optional" just initialize the attributes.

like image 94
extrablade Avatar answered Nov 18 '25 21:11

extrablade


In Swift 5 you can create a new func in your class:

func debugLog() {
    print(Mirror(reflecting: self).children.compactMap { "\($0.label ?? "Unknown Label"): \($0.value)" }.joined(separator: "\n"))
}

And then call it with MyObject().debugLog()

like image 28
Radu Ursache Avatar answered Nov 18 '25 20:11

Radu Ursache



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!