Skip to content

Instantly share code, notes, and snippets.

@AndreyPanov
Last active March 17, 2017 17:15
Show Gist options
  • Save AndreyPanov/2d56c409ce6adff9ef57ba3c48239236 to your computer and use it in GitHub Desktop.
Save AndreyPanov/2d56c409ce6adff9ef57ba3c48239236 to your computer and use it in GitHub Desktop.
Reflection Generic Properties
import UIKit
protocol Reflectable {
func properties<T>() -> [T]
}
extension Reflectable {
func properties<T>() -> [T] {
var s = [T]()
Mirror(reflecting: self).children.forEach { property in
if let value = property.value as? T {
s.append(value)
}
}
return s
}
}
//Example
class Upcoming: Reflectable {
let driverLabel = UILabel()
let passengerLabel = UILabel()
let estimationLabel = UILabel()
let driverText = UITextField()
let passengerText = UITextField()
let estimationText = UITextField()
func setup() {
let labels: [UILabel] = properties()
labels.forEach { $0.text = "1234" }
let textFields: [UITextField] = properties()
textFields.forEach { $0.text = "5678" }
print(driverLabel.text ?? "") // 1234
print(passengerLabel.text ?? "") // 1234
print(estimationLabel.text ?? "") // 1234
print(driverText.text ?? "") // 5678
print(passengerText.text ?? "") // 5678
print(estimationText.text ?? "") // 5678
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment