How do I set Swift values by property name?
Asked Answered
F

1

6

Objective-C has a setValue method which allows the developer to set a specific value to a field by it's name.

How can I do that in Swift without inheriting from NSObject and actually use the setValue method?

Fishwife answered 21/9, 2015 at 12:20 Comment(1)
Have you looked at #24092785 ?Greathouse
B
2

You can use KVC to do so, afaik. Have a look at this cool example: https://www.raywenderlich.com/163857/whats-new-swift-4

struct Lightsaber {
  enum Color {
    case blue, green, red
  }
  let color: Color
}

class ForceUser {
  var name: String
  var lightsaber: Lightsaber
  var master: ForceUser?

  init(name: String, lightsaber: Lightsaber, master: ForceUser? = nil) {
    self.name = name
    self.lightsaber = lightsaber
    self.master = master
  }
}

let sidious = ForceUser(name: "Darth Sidious", lightsaber: Lightsaber(color: .red))
let obiwan = ForceUser(name: "Obi-Wan Kenobi", lightsaber: Lightsaber(color: .blue))
let anakin = ForceUser(name: "Anakin Skywalker", lightsaber: Lightsaber(color: .blue), master: obiwan)

// Use keypath directly inline and to drill down to sub objects
let anakinSaberColor = anakin[keyPath: \ForceUser.lightsaber.color]  // blue

// Access a property on the object returned by key path
let masterKeyPath = \ForceUser.master
let anakinMasterName = anakin[keyPath: masterKeyPath]?.name  // "Obi-Wan Kenobi"

// AND HERE's YOUR ANSWER
// Change Anakin to the dark side using key path as a setter
anakin[keyPath: masterKeyPath] = sidious
anakin.master?.name // Darth Sidious
Bricole answered 17/7, 2017 at 14:49 Comment(1)
this solution is not the author wanted, you cannot get the key path from a string.Pemphigus

© 2022 - 2024 — McMap. All rights reserved.