Swift相当于字符串文字界面? - `request(方法:'post'|'put')`

时间:2018-02-20 04:39:20

标签: swift function types swift4 swift-protocols

在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函数的允许输入?

2 个答案:

答案 0 :(得分:0)

您的大写已关闭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中所做的那样,您可能会以这种方式编写它以获得相同的东西。 String枚举自动是它自己的值。

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

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

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

func request(method: HTTPMethod)

答案 1 :(得分:0)

概述:

  • 使用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])

参见: