Created
May 24, 2018 07:09
-
-
Save mastermind247/ea54376de05114627003b58d817dd66c to your computer and use it in GitHub Desktop.
Iterate through structures and print all properties
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 | |
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