Last active
April 1, 2018 05:29
-
-
Save guidomb/944dac933caf12946384e0a33575ff82 to your computer and use it in GitHub Desktop.
Conditional conformace compiler bug?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public protocol QueryStringConvertible { | |
var asQueryString: String { get } | |
} | |
extension Array: QueryStringConvertible where Element: QueryStringConvertible { | |
public var asQueryString: String { | |
return self.reduce("") { $0.isEmpty ? $1.asQueryString : "\($0)&\($1.asQueryString)" } | |
} | |
} | |
extension Dictionary: QueryStringConvertible where Key == String, Value: CustomStringConvertible { | |
public var asQueryString: String { | |
return self.reduce("") { ($0.isEmpty ? "" : "\($0)&") + "\($1.key)=\($1.value)" } | |
} | |
} | |
struct Person: QueryStringConvertible { | |
let firstName: String | |
let lastName: String | |
public var asQueryString: String { | |
return "firstName=\(firstName)&lastName=\(lastName)" | |
} | |
} | |
func bar<Q: QueryStringConvertible>(query: Q) -> String{ | |
return "QUERY: " + query.asQueryString | |
} | |
func baz(query: QueryStringConvertible) -> String { | |
return "QUERY: " + query.asQueryString | |
} | |
let dictionary = [ "param1" : "value1", "param2" : "value2" ] | |
dictionary.asQueryString | |
let person = Person(firstName: "John", lastName: "Doe") | |
person.asQueryString | |
bar(query: dictionary) | |
bar(query: person) | |
bar(query: [dictionary]) | |
bar(query: [person]) | |
// THIS does not compile -> '<Q where Q : QueryStringConvertible> (query: Q) -> String' requires that 'Any' conform to 'QueryStringConvertible' | |
bar(query: [dictionary, person]) | |
baz(query: dictionary) | |
baz(query: person) | |
baz(query: [dictionary]) | |
baz(query: [person]) | |
// This does not compile -> Contextual type 'QueryStringConvertible' cannot be used with array literal | |
baz(query: [dictionary, person]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment