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 : "abcd@xyz.com")
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 abcd@xyz.com
There can be many solutions to your problem. I think my solution could give an idea of how can you solve this problem.
struct Student {
var rollNum: Int
var name: String
var contact: Contact
}
struct Contact {
var phoneNum: String
var mailId: String
}
func studentInformation(student: Student, paths: [String]) {
print("Student name: \(student.name), RollNumber: \(student.rollNum)")
if paths[0] == "\(Contact.self)" {
contactInformation(contact: student.contact, path: paths[1])
}
}
func contactInformation(contact: Contact, path: String) {
print("Contact phonenumber: \(contact.phoneNum), mailId: \(contact.mailId)")
let contactVariableNameWithValue = Mirror(reflecting: contact).children
for variableName in contactVariableNameWithValue {
if variableName.label == path {
print(variableName.value)
break
}
}
}
let contact = Contact(phoneNum: "1234567890", mailId: "abcd@xyz.com")
let student = Student(rollNum: 1, name: "John", contact: contact)
var pathString = "Student/Contact/mailId"
public let pathComponents = pathString.components(separatedBy: "/")
studentInformation(student: student, paths: Array(pathComponents.suffix(from: 1)))
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: "official@gmail.com", personal: "personal@gmail.com"))
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 personal@gmail.com
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.