您的问题可以有很多解决方案。我认为我的解决方案可以让您了解如何解决这个问题。
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)))