如何在 swift 中打印变量名?

How to print variable name in swift?

我们如何在 swift 中打印变量名?这类似于这个问题讨论的内容 Get a Swift Variable's Actual Name as String 我无法从上面的 QA 中弄清楚如何根据我的需要在 swift 中打印它,如下所述

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
} 

您可以将结构更改为枚举

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


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

示例

doSomething(endPoint: .apiEndPoint)

apiEndPoint: example.com/profile?

您可以使用 Mirror 进行反思并做一些像这样的傻事:

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)

但我绝不会推荐做这样的事情,并且像建议的其他答案一样使用枚举可能是可行的方法。

我喜欢 Quinn 的方法,但我相信它可以更简单地完成:

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

    func name(for string: String) -> String? {
        Mirror(reflecting: self).children
            .first { [=10=].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