[swift-evolution] [Idea] Use optionals for non-optional parameters

Xiaodi Wu xiaodi.wu at gmail.com
Mon Aug 15 02:13:39 CDT 2016


It has been mentioned before (more than once, perhaps, but not in its own
thread I don't think, so good luck finding it). IIRC, one of the problems
is that it's unclear what happens if your function takes multiple
arguments. Does evaluation proceed from left to right? does it
short-circuit? Put concretely:

```
func bar(_ x: Int) -> Int? { /* side effects */ }
func baz(_ y: Int) -> Int? { /* side effects */ }
func foo(_ z: Int, _ a: Int) -> Int { /* ... */ }

print(foo(bar(42)?, baz(42)?))
```

Does baz(42) get evaluated if bar returns nil? Does bar(42) get evaluated
if baz returns nil?


On Mon, Aug 15, 2016 at 2:02 AM, Justin Jia via swift-evolution <
swift-evolution at swift.org> wrote:

> Hi!
>
> I don’t know if this has came up before. I tried to search though the
> mailing list but didn’t find any related threads.
>
> This is purely a syntactic thing (which I know it’s the lowest priority
> for Swift 4), but I think it’s an important one.
>
> Let’s say we have a struct with a function:
>
> ```
> struct Foo {
>     func bar(x: Int)
> }
> ```
>
> We can use optionals:
>
> ```
> let foo: Foo? = nil
> let x = 1
> foo!.bar(x: x) // Able to compile, but will cause runtime error
> foo?.bar(x: x) // Able to compile, and won't cause runtime error
> ```
>
> However:
>
> ```
> let foo = Foo()
> let x: Int? = nil
> foo.bar(x: x!) // Able to compile, but will cause runtime error
> foo.bar(x: x?) // Won't compile
> ```
>
> I propose that we should allow `foo.bar(x: x?)`, which should be
> equivalent to:
>
> ```
> if let x = x {
>   foo.bar(x: x)
> }
> ```
>
> What do you think?
>
> Thanks,
> Justin
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160815/8f362dc7/attachment.html>


More information about the swift-evolution mailing list