swift 如何从类型链中获取字符串?

yqkkidmi  于 2023-03-07  发布在  Swift
关注(0)|答案(1)|浏览(156)

我把服务器API分成几组。我试着构建一个结构体来获得字符串形式的API。
例如我尝试了类似这样的东西

struct ServerApi {
    enum Auth {
        case login
        case logout
        
        var string: String {
            "/\(Self.self)".lowercased() + "/\(self)"
        }
    }
    enum App {
        case version
        case webapiVersion
        case buildInfo
        
        var string: String {
            "/\(Self.self)".lowercased() + "/\(self)"
        }
    }
    ...
    ...
    enum GroupA {
        case versionA
        case webapiVersionA
        case buildInfoA
        
        var string: String {
            "/\(Self.self)".lowercased() + "/\(self)"
        }
    }
}

有没有一种方法可以获得枚举属性的字符串完整描述路径,而无需在每个枚举中写入string计算属性?

8tntrjer

8tntrjer1#

https://docs.swift.org/swift-book/documentation/the-swift-programming-language/protocols#Protocol-Extensions

protocol string { }
extension string {
  var string: String {
    "/\(Self.self)".lowercased() + "/\(self)"
  }
}

相关问题