[swift-evolution] allowing to specify optionality with type inference

Hugues Bernet-Rollande hugues at xdev.fr
Thu Mar 24 05:22:30 CDT 2016

In a strongly typed language, such as Swift is, type inference is greatly
appreciated as it declutter the instance type definition.


For example, in the following statement, the compiler easily deduct the type
of `aString` by the return type of `String.init()`



let aString = String()



Optional are generic enum which can contain a value of a generic type or nil


Sometime you may want specify that the instance is of type optional in which
even if you are a the same time assigning a value to this instance.

In which case you loose the type inference mechanism and you have to define
both (the optionality as well as the type).

For example, you may want specify an optional String with a default value.



var a:String? = String()

// or

var b = String() as String?

// or

var c:Optional<String> = String()  



But the compiler can already infer the variable type from this assignment, it
just miss the "optionality" of the variable.

It would be nice to be able to express this.


Then for, I propose the following syntax evolution:



var a:? = String()

// and/or (not recommended because more prone to typo and unclear...)

var a = String() as?



This would allow for more synthetic optional declaration.


I've draft a proposal on my `swift-evolution` fork:



Let me know what you think.






hugues at xdev.fr



-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160324/a7e6e623/attachment.html>

More information about the swift-evolution mailing list