0

I have a struct name called Car. Car has two attributes(noOfTyres, ownerName).

struct Car {
    var noOfTyres: Int
    var ownerName: String
}

The string value is let objStr = "Car/ownerName"

how to convert the objStr to swiftObject like Car.ownerName?

ThomasW
  • 16,981
  • 4
  • 79
  • 106
S Surya
  • 87
  • 1
  • 1
  • 8
  • swift isn't to strong when it comes to reflection so you need to do this manually. Like parsing this string and using a `switch` but it is actually unclear what your end goal is here. How exactly do you want to use Car.ownerName? – Joakim Danielson Feb 22 '22 at 09:29
  • Why duplicate: https://stackoverflow.com/questions/71218355/convert-path-string-to-object-path-in-swift ? – Larme Feb 22 '22 at 09:34
  • add initialiser with string value and parse it how you like – Cy-4AH Feb 22 '22 at 09:41
  • `Struct Car` should be `struct Car`. There is no object like `Car.ownerName`, `ownerName` is not a static var of `Car`. This looks like the same school assignment as @Larme duplicate comment. – workingdog support Ukraine Feb 22 '22 at 10:04

2 Answers2

0

you could try something like this:

let str = "Car/ownerName"
let obj = Car.toObj(str)
print("---> obj: \(obj)")   // --> optional "xxxx"

struct Car {
    var noOfTyres: Int
    static var ownerName: String = "xxxx"
    
    static func toObj(_ str: String) -> String? {
        if str.prefix(4) == "Car/" && str.dropFirst(4) == "ownerName" {
            return Car.ownerName  // <-- here
        } else {
            return nil
        }
    }
}
-2

You can create struct object by below code:

struct Car {
    var noOfTyres: Int
    var ownerName: String
}
class Demo {
    func createStructObject() {
        var structData = [Car]()
        structData.append(Car(noOfTyres: 2, ownerName: "Innova"))
        let name = structData[0].ownerName
        print(name)
    }
}
  • 3
    How is this relevant to the question being asked? – Joakim Danielson Feb 22 '22 at 09:30
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 22 '22 at 15:08