Ben Harold
Ben Harold

Reputation: 6432

Is it possible to access a struct member using a variable in Swift 4?

I've got a list of instances of the following struct called payment_list:

struct Payment: Codable {

    let id: Int
    let payment_hash: String
    let destination: String
    let msatoshi: Int
    let timestamp: Int
    let created_at: Int
    let status: String

    enum PaymentKeys: String, CodingKey {
        case payments
    }
}

I can access the members of each struct instance in the list in the following manner:

print(payment_list[0].id)        // 1 
print(payment_list[0].timestamp) // 1517083775

Is it possible to access those struct instance members using a variable to determine which member is being accessed? Something along the lines of:

var column = "id"
print(payment_list[0][column]) // 1

I've read about people using NSObject and value(forKey key: String), but this is a struct so it can't inherit from NSObject. If it was an object I think it would look something like this:

var column = "id"
print(payment_list[0].value(forKey key: column)) // 1

Is this type of thing possible with struct?

Upvotes: 0

Views: 483

Answers (1)

dr_barto
dr_barto

Reputation: 6075

Swift 4 added support for key paths, which allow to do something similar to what you want:

let keyPath: KeyPath<Payment, Int> = \Payment.id
var payment = Payment(id: 42)
let value = payment[keyPath: keyPath] // returns 42

A key path has two generic parameters: first the type it operates on (in your example Payment), and the type of the property it accesses (Int). Note that you'll have to specify the key path for every property you want to access.

Upvotes: 4

Related Questions