Last active
January 24, 2020 22:52
-
-
Save minikin/450f83d74d27a8b2b8b527e8766b1222 to your computer and use it in GitHub Desktop.
Iterate over object class attributes in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I don't know why do you want to use these techniques nowadays. I'm sure that
KeyPath
is a more convenient way.