Skip to content

Instantly share code, notes, and snippets.

@mastermind247
Created May 24, 2018 07:09
Show Gist options
  • Save mastermind247/ea54376de05114627003b58d817dd66c to your computer and use it in GitHub Desktop.
Save mastermind247/ea54376de05114627003b58d817dd66c to your computer and use it in GitHub Desktop.
Iterate through structures and print all properties
import UIKit
import Foundation
protocol Printable {
func getAllProperties() -> [String: Any]?
}
extension Printable {
func getAllProperties() -> [String: Any]? {
var result: [String: Any] = [:]
let mirror = Mirror(reflecting: self)
guard let style = mirror.displayStyle, style == .struct else {
return nil // If not struct then return
}
for (property, value) in mirror.children {
guard let property = property else {
continue
}
result[property] = value
}
return result
}
}
protocol CarMake: Printable {
// Additional requirements
}
struct Mercedes: CarMake {
var carBody = "Metal"
var classType = "E-Class"
}
struct BMW: CarMake {
var model = "BMW 750d"
var bodyColor = "Phantom Black"
}
struct Volvo: CarMake {
var modelName = "Volvo S90"
var price = "$50000"
}
func getCarMake(with carMake: CarMake) {
if let properties = carMake.getAllProperties() {
print(properties)
}
}
let mercedes = Mercedes()
let bmw = BMW()
let volvo = Volvo()
getCarMake(with: mercedes)
getCarMake(with: bmw)
getCarMake(with: volvo)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment