Can associated values and raw values coexist in Swift enumeration?

后端 未结 5 1784
遇见更好的自我
遇见更好的自我 2020-12-04 19:22

There are examples on Swift book demonstrating associated values and raw values separately, is there a way to define enums with the two features together?

I have tri

5条回答
  •  隐瞒了意图╮
    2020-12-04 20:02

    The answers here are great, but don't provide an alternative, so here is one:

    I'm trying to write a convenient wrapper for Parse.com's rest API, and honestly this restriction imposed by swift made me write a bit more code, but the end result is more readable:

    class Parse {
    
        enum Endpoint {
            case signUp(ParseHTTPBody)
            case login(ParseHTTPBody)
        }
    
    }
    
    extension Parse.Endpoint {
    
        var httpMethod: String {
            switch self {
            case .signUp, .login:
                return "POST"
            }
        }
    
        var path: String {
            switch self {
            case .signUp:
                return "/1/users"
            case .login:
                return "/1/login"
            }
        }
    }
    

    Notice, now I httpMethod and path instead of rawValue, which is more readable in my case:

    func setParseEndpoint(endpoint: Parse.Endpoint) -> Self {
    
        URL = NSURL(string: baseURL + endpoint.path)
        HTTPMethod = endpoint.httpMethod
    
        return self
    }
    

提交回复
热议问题