Reputation: 1258
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
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
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
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