如何快速打印变量名?

时间:2020-01-30 19:15:27

标签: swift swift5

如何快速打印变量名?类似于该问题讨论的Get a Swift Variable's Actual Name as String 我无法从QA的上面弄清楚如何按照我的需要快速打印它,如下所述

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
} 

3 个答案:

答案 0 :(得分:5)

您可以将结构更改为枚举

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?

答案 1 :(得分:2)

您可以使用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)

但是我永远不建议这样做,使用像其他建议的枚举之类的枚举可能是解决方法。

答案 2 :(得分:0)

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

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
相关问题