Andrej Andrej - 6 months ago 10
Swift Question

Function to return object's property

I'd like to change an object's parameter, but I like to decide later about what's the parameter that should change. I'm thinking to make a function for that, but don't know how. Here's a sample:

class Car {
var color = "green"
var brand = "Zastava"
var mechanic = "Mark Gaia"
}

struct Change {
var property: String
var newValue: String
}

let car = Car()
let change = Change(property: "brand", newValue: "Fiat")
car.propertyFromChange(change) = change.newValue // ??? How to implement this line


How to make a function that returns what's the parameter of an object that needs to be changed?

Alternatively, how to choose which parameter to change?

(...I thought about
switch
statement. Is a good direction?)

I'm pretty sure that's something that has already been discussed on internet. I've read everything about functions and couldn't find the solution, so I guess I'm searching using wrong keywords.

Answer

You don't need to create a function you can use KVC like this after you inherit from NSObject, or you can make a new func that guards again bad property names.

class Car: NSObject {
    var color = "green"
    var brand = "Zastava"
    var mechanic = "Mark Gaia"
}

struct Change {
    var property: String
    var newValue: String
}

let car = Car()
let change = Change(property: "brand", newValue: "Fiat")
car.setValue(change.newValue, forKey: change.property)

Keep in mind that this code will crash if you enter bad property names.

Hope this answers your question.