【问题标题】:Swift equivalent of string literal interfaces? - `request(method: 'post'|'put')` [closed]Swift相当于字符串文字接口? -`request(方法:'post'|'put')`[关闭]
【发布时间】:2018-07-30 09:12:07
【问题描述】:

在 TypeScript 中我可以做这样的事情 [docs]:

request(method: 'post'|'put')

但在 Swift 中,我正在编写糟糕的代码,例如:

// See RFC7231 and RFC5789 for more info
enum HttpMethods: String {
    case GET = "GET"
    case HEAD = "HEAD"
    case POST = "POST"
    case PUT = "PUT"
    case DELETE = "DELETE"
    case CONNECT = "CONNECT"
    case OPTIONS = "OPTIONS"
    case TRACE = "TRACE"
    case PATCH = "PATCH"
}

如何在编译时限制 Swift 函数的允许输入?

【问题讨论】:

    标签: swift function types swift4 swift-protocols


    【解决方案1】:

    您的 Swift 大写已关闭。你的意思可能是:

    enum HTTPMethod: String {
        case get = "GET"
        case head = "HEAD"
        case post = "POST"
        case put = "PUT"
        case delete = "DELETE"
        case connect = "CONNECT"
        case options = "OPTIONS"
        case trace = "TRACE"
        case patch = "PATCH"
    }
    

    如果小写字符串常量没问题,就像你在 Typescript 中所做的那样,你可能会这样写来得到同样的东西。一个字符串枚举自动是它自己的值。

    enum HTTPMethods: String {
        case get, head, post, put, delete, connect, options, trace, patch
    }
    

    如果你想有小写的常量名,但大写的字符串值,那么你需要使用第一个版本。

    要使用它来限制参数,您只需使用类型:

    func request(method: HTTPMethod)
    

    【讨论】:

    • 啊是的,就是这样。知道我在正确的轨道附近:P
    【解决方案2】:

    概述:

    • 使用OptionSet 支持多个值。

    代码:

    struct HTTPMethod : OptionSet {
    
        let rawValue : Int
    
        static let get      = HTTPMethod(rawValue: 1 << 0)
        static let head     = HTTPMethod(rawValue: 1 << 1)
        static let post     = HTTPMethod(rawValue: 1 << 2)
        static let put      = HTTPMethod(rawValue: 1 << 3)
        static let delete   = HTTPMethod(rawValue: 1 << 4)
        static let connect  = HTTPMethod(rawValue: 1 << 5)
        static let trace    = HTTPMethod(rawValue: 1 << 6)
        static let patch    = HTTPMethod(rawValue: 1 << 7)
    }
    
    func doSomething(method: HTTPMethod) {
    
    
    }
    
    doSomething(method: [.get, .head, .put])
    

    参考:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-06
      相关资源
      最近更新 更多