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
?
CodePudding user response:
you could try something like this:
let str = "Car/ownerName"
let obj = Car.toObj(str)
print("---> obj: \(obj)") // "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
} else {
return "" // or nil if desired
}
}
}
CodePudding user response:
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)
}
}