[swift-evolution] Implicit Optionals for Tuples & Tuples as Function Parameter

Haravikk swift-evolution at haravikk.me
Fri Nov 11 14:52:33 CST 2016


> On 11 Nov 2016, at 19:54, Muhammad Tahir Vali via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Im curious to know the reasoning behind why implicit-wrapped optionals aren't allowed when creating tuples. Below is an example with type aliases and anonymous tuples.
> 
> ex. 
> typealias Name = (first: String!, middle: String?, last: String!)
> typealias Name = (first: String!, middle: String?, last: String!)!
> var name : (first: String!, middle: String?, last: String!)
> var name : (first: String!, middle: String?, last: String!)!
> 
> error from all 4 examples above:
> Implicitly unwrapped optionals are only allowed at top level and as function results

I think in general the direction is leaning towards getting rid of IUO's entirely if possible, as a lot of things that people use them for could be handled better in other ways; the only times I've ever used them is to get around issues with constructors (namely the requirement to initialise everything before other methods can be called), but that could be solved by detecting or marking methods that would be safe for that.

> I also noticed that I can modify tuples using functions ONLY if I use inout. 
> 
> func name(Person : inout (first: String?, middle: String?, last: String?)) {
>     Person.first = "John"
>     Person.last = "Doe"
> }
> 
> OR 
> 
> func name(Person : inout Name) {
>     Person.first = "John"
>     Person.last = "Doe"
> }
> 
> This is because tuples are passed into functions as 'let' constants. Why not add the ability to modify a copy of the tuple inside the function ?

The ability to specify function arguments as mutable was removed to avoid confusion with inout as it wasn't completely obvious that with a var what you're modifying is a copy. However you can make a mutable copy with shadowing, like-so:

	func name(Person:(first:String?, middle:String?, last:String?) { var Person = Person // Person is now a mutable copy
		Person.first = "John"
		Person.last = "Doe"
	}

Obviously with the caveat that these changes don't exist outside of that scope, so unless you make use of them there that code will likely just get optimised away.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20161111/2ac53f31/attachment.html>


More information about the swift-evolution mailing list