Last active
March 17, 2017 17:15
-
-
Save AndreyPanov/2d56c409ce6adff9ef57ba3c48239236 to your computer and use it in GitHub Desktop.
Reflection Generic Properties
This file contains hidden or 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 | |
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