I'm a bit undecided, as it seems like it doesn't add enough to warrant another 
operator to learn (and one that's a bit confusing in its purpose, since it 
doesn't trap like other exclamation mark operators do).

For the specific example you can already just do:

        func query(name:String?) -> String { return "{ param: \"" + (name ?? 
"null") + "\" }" }

In the case where the input value isn't an optional string you can still do:

        func myFunc(foo:Foo?) -> String { return foo?.description ?? "null" }

I dunno, I'm just not sure having another ternary adds quite enough to justify 
it, and like I say it's a bit of an odd operator since it doesn't actually 
trap. For the specific case of a String a more useful alternative might be the 
ability to put the ?? operator inside a string, with the compiler knowing the 
final type must be a String (so you can mix types as long as they're 
CustomStringConvertible), like so:

        func query(name:String?) -> String { return "{ param: \"\(name ?? 
"null")\"" }

> On 8 Feb 2017, at 14:04, Maxim Veksler via swift-evolution 
> <swift-evolution@swift.org> wrote:
> 
> Hello, 
> 
> Let's assume I have an optional "name" parameter, based on the optional 
> status of the parameters I would like to compose string with either the 
> unwrapped value of name, or the string "null". The use case for is syntactic 
> sugar to compose a GraphQL queries.
> 
> A (sampled) illustration of the code that currently solves it looks as 
> following:
> 
> func query(name: String?) {
>   let variables_name = name != nil ? "\"\(name!)\"" : "null"
>   return "{ param: \(variables_name) }"
> }
> 
> Based on optional status the following output is expected
> 
> let name = "Max"
> query(name: name) 
> // { param: "Max" }
> 
> let name: String? = nil
> query(name: name)
> // { param: null }
> 
> I think it might be useful to have an conditional unwrap operator !? that 
> would enable syntax sugar uch as the following built into the language:
> 
> func query(name: String?) {
>   return "{ param: \(name !? "\"\(name)\"": "null") }"
> }
> 
> This expression is expected to produce same output as the examples above. It 
> means check the Optional state of name: String?, in case it has a value, 
> unwrap it and make the unwrapped value accessible under the same name to the 
> true condition part of the expression, otherwise return the false condition 
> part of the expression.
> 
> The effectively removes the need to have the "if != nil" and the forced 
> unwrap syntactical code, and IMHO improves code readability and 
> expressiveness.
> 
> I'm wondering what the community thinks of the displayed use case, and 
> proposed solution?

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

Reply via email to