Raymond
Raymond

Reputation: 1258

How to print variable name in swift?

How do we print variable name in swift? It's similar to what this question discusses Get a Swift Variable's Actual Name as String I can't figure out from above QA how to print it in swift for my need as described below

struct API {
    static let apiEndPoint = "example.com/profile?"
    static let apiEndPoint1 = "example.com/user?"
 }

doSomething(endPoint: API.apiEndPoint)
doSomething(endPoint: API.apiEndPoint1)

func doSomething(endPoint: String) {
    // print the variable name which should be apiEndPoint or endPoint1
} 

Upvotes: 0

Views: 3811

Answers (3)

Rob Napier
Rob Napier

Reputation: 299275

I like Quinn's approach, but I believe it can be done more simply:

struct API {
    let apiEndPoint = "example.com/profile?"
    let apiEndPoint1 = "example.com/user?"

    func name(for string: String) -> String? {
        Mirror(reflecting: self).children
            .first { $0.value as? String == string }?.label
    }
}

func doSomething(endPoint: String) {
    print(API().name(for: endPoint)!)
}

let api = API()

doSomething(endPoint: api.apiEndPoint) // apiEndPoint
doSomething(endPoint: api.apiEndPoint1) // apiEndPoint1

Upvotes: 1

Quinn
Quinn

Reputation: 9404

You could use Mirror for reflection and do something silly like this:

struct API {
    let apiEndPoint = "example.com/profile?"
    let apiEndPoint1 = "example.com/user?"
}

func doSomething(api: API, endPoint: String) {
    let mirror = Mirror(reflecting: api)

    for child in mirror.children {
        if (child.value as? String) == endPoint {
            print(child.label!) // will print apiEndPoint
        }
    }
}

let api = API()

doSomething(api: api, endPoint: api.apiEndPoint)
doSomething(api: api, endPoint: api.apiEndPoint1)

But I would never recommend doing something like this, and using an enum like the other answer suggested is probably the way to go.

Upvotes: 2

Joakim Danielson
Joakim Danielson

Reputation: 51892

You could change your struct to an enum

enum API: String {
    case apiEndPoint = "example.com/profile?"
    case apiEndPoint1 = "example.com/user?"
 }


func doSomething(endPoint: API) {
    print("\(endPoint): \(endPoint.rawValue)")
}

Example

doSomething(endPoint: .apiEndPoint)

apiEndPoint: example.com/profile?

Upvotes: 5

Related Questions