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?

4
  • 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? Commented Feb 22, 2022 at 9:29
  • Why duplicate: stackoverflow.com/questions/71218355/… ? Commented Feb 22, 2022 at 9:34
  • add initialiser with string value and parse it how you like Commented Feb 22, 2022 at 9: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. Commented Feb 22, 2022 at 10:04

2 Answers 2

1

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
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

-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)
    }
}

2 Comments

How is this relevant to the question being asked?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.