[swift-evolution] [Idea] Use optionals for non-optional parameters
Justin Jia
justin.jia.developer at gmail.com
Mon Aug 15 02:02:34 CDT 2016
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
More information about the swift-evolution
mailing list