[swift-evolution] The bind thread

Brent Royal-Gordon brent at architechies.com
Mon Feb 1 17:23:20 CST 2016


>   if bind foo {
>       // foo is non-optional in here
>   }

If something in a flow control statement should read like an assertion, we don't want "bind" here.

	if has foo {
		// foo is non-optional
	}

However, I do note that pattern matching in an if statement already lets you do the same thing as `if let` more explicitly:

	if case let foo? = bar {
		
	}

I wonder if we should instead enhance this feature's usability. For instance, as a surgical change, we could drop the `case` keyword when `let` is present in the condition (since `let` isn't allowed in a boolean expression anyway):

	if let foo? = bar {
		
	}

This is one character longer than the current `if let`, but it falls naturally out of other language features and allows for other similar constructs, like `if let .Success(value) = bar`.

However, the `if case` syntax kind of sucks in other ways, too, and I think it deserves another look. In particular, the `=` isn't great for pattern matching that doesn't bind variables; people have complained about that part of `if case` before. Maybe we can improve that while still making the unwrapping good by introducing a keyword or operator that replaces the `=` while implying the `case` so it doesn't have to be stated explicitly. Here's a strawman of what this would look like, using `matches`:

	if let foo? matches bar
	if let .Success(value) matches bar
	if .Card(let rank, .Heart) matches bar
	if .OK matches bar

Can we do this with `for case` too? Maybe...

	for let foo? matches in bars
	for let .Success(value) matches in bars
	for .Card(let rank, .Heart) matches in bars
	for .OK matches in bars

I think this approach might work; the only question is what `matches` should be. I don't like using a keyword for it; I think it disappears too easily, particularly in the optional case. We do sort of have a pattern matching operator, `~=`, but it's very obscure, the overloading is not really right, and I can never remember which order the characters go in (possibly because Perl uses `=~` as its matching operator). Colon kind of reads well, but it disappears too easily, and it's already associated with typing:

	if let foo?: bar
	if let .Success(value): bar
	if .Card(let rank, .Heart): bar
	if .OK: bar

I don't know what the answer is here, but I think this might be a good line to pursue.

-- 
Brent Royal-Gordon
Architechies



More information about the swift-evolution mailing list