Search code examples
swiftswift-string

Convert Path String to Object Path in Swift



struct Student{
  var rollNum : Int
  var name : String
  var contact : Contact
}
struct Contact{
  var phoneNum : String
  var mailId : String
}

let contact = Contact(phoneNum : "1234567890", mailId : "[email protected]") 
let student = Student(rollNum : 1, name : "John", contact : contact)

Here, the path for mail Id is given as a String "Student/contact/mailId". How to convert this to Object Path as Student.contact.mailId?

Assume the label wants to display the mail ID, I would give the path string as "Student/contact/mailId" and the label should display the mail id as [email protected]


Solution

  • struct Student {
        var rollNum: String
        var name: String
        var contact: Contact
    }
    struct Contact {
        var phoneNum: String
        var mailId: MailId
    }
    struct MailId {
        var official : String
        var personal : String
    }
    let pathString = "Student/contact/mailId/personal"
    let pathComponents = pathString.components(separatedBy: "/")
    var index : Int = 1
    
    let contact = Contact(phoneNum: "9988998899", mailId: MailId(official: "[email protected]", personal: "[email protected]"))
    let student = Student(rollNum: "123", name: "John", contact: contact)
    
    
    
    Reflection(from: student , pathComponents: pathComponents)
    func Reflection(from object : Any, pathComponents : [String]) {
        let properties = Mirror(reflecting: object)
        for property in properties.children{
            if index < pathComponents.count{
                if property.label == pathComponents[index] {
                    index += 1
                    print(property.value , "got here with label :" , property.label)
                    Reflection(from: property.value, pathComponents: pathComponents)
                    
                }
            }
        }
    }
    

    Here, we can get the value as [email protected]