Skip to content

Instantly share code, notes, and snippets.

@minikin
Last active January 24, 2020 22:52
Show Gist options
  • Save minikin/450f83d74d27a8b2b8b527e8766b1222 to your computer and use it in GitHub Desktop.
Save minikin/450f83d74d27a8b2b8b527e8766b1222 to your computer and use it in GitHub Desktop.
Iterate over object class attributes in Swift
import UIKit
struct User {
var name = ""
var lastName = ""
var nickName = ""
var age = 0
}
var user = User()
user.name = "Sasha"
user.lastName = "Prokhorenko"
user.nickName = "minikin"
user.age = 35
let mirrored_object = Mirror(reflecting: user)
for (index, attr) in mirrored_object.children.enumerated() {
if let propertyName = attr.label as String! {
print("Attr \(index): \(propertyName) = \(attr.value)")
}
}
@minikin
Copy link
Author

minikin commented Jan 24, 2020

I don't know why do you want to use these techniques nowadays. I'm sure that KeyPath is a more convenient way.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment