Convert dictionary to query string in swift?

前端 未结 11 777
走了就别回头了
走了就别回头了 2021-01-04 04:37

I have a dictionary as [String:Any].Now i want to convert this dictionary keys & value as key=value&key=value.I have created below extensio

相关标签:
11条回答
  • 2021-01-04 05:01
    protocol ParametersConvertible {
        func asParameters() -> [String:Any] 
    }
    
    protocol QueryStringConvertible {
        func asQuery() -> String
    }
    
    extension QueryStringConvertible where Self: ParametersConvertible {
        func asQuery() -> String {
            var queries: [URLQueryItem] = []
            for (key, value) in self.asParameters() {
                queries.append(.init(name: key, value: "\(value)"))
            }
    
            guard var components = URLComponents(string: "") else {
                return ""
            }
    
            components.queryItems = queries
            return components.percentEncodedQuery ?? ""
        }
    }
    
    0 讨论(0)
  • 2021-01-04 05:04

    For anyone that wants the "short, short" version.

    Condensed using map, you don't need the forEach or for loops. Also protocol constrained for type enforcement on the dictionary.

    extension Dictionary where Key : StringProtocol, Value : StringProtocol {
        var queryString: String {
            self.map { "\($0)=\($1)" }.joined(separator: "&")
        }
    }
    
    0 讨论(0)
  • 2021-01-04 05:09

    Another Swift-esque approach:

    let params = [
        "id": 2,
        "name": "Test"
    ]
    
    let urlParams = params.flatMap({ (key, value) -> String in
        return "\(key)=\(value)"
    }).joined(separator: "&")
    
    0 讨论(0)
  • 2021-01-04 05:11

    Same as @KKRocks with update for swift 4.1.2

    func queryItems(dictionary: [String:Any]) -> String {
        var components = URLComponents()
        print(components.url!)
        components.queryItems = dictionary.map {
            URLQueryItem(name: $0, value: String(describing: $1))
        }
       return (components.url?.absoluteString)!
    }
    
    0 讨论(0)
  • 2021-01-04 05:14
    extension Dictionary {
        var queryString: String? {
            return self.reduce("") { "\($0!)\($1.0)=\($1.1)&" }
        }
    }
    
    0 讨论(0)
  • 2021-01-04 05:17

    Try this :

    func queryItems(dictionary: [String:Any]) -> String {
            var components = URLComponents()
            print(components.url!)
            components.queryItems = dictionary.map {
                URLQueryItem(name: $0, value: $1)
            }
           return (components.url?.absoluteString)!
        }
    
    0 讨论(0)
提交回复
热议问题