[swift-evolution] Splat

Brent Royal-Gordon brent at architechies.com
Thu Feb 11 01:54:25 CST 2016


> Still find it quite confusing, because I expected x.methodName to be a bound method and here it's a special syntactic form.  What happens if a protocol defines "func apply(to:)"?  Is that legal?  Would function types automatically conform to the protocol?

For `apply(to:)`, it really would just be a method available on function types. You could put an `apply(to:)` method on any other type, and it wouldn't have any effect on things. You could declare a protocol with `apply(to:)`, but it wouldn't do anything to any function types. Conceptually, there would only be a few special things about them:

1. The compiler generates the `apply(to:)` methods automatically. We could, perhaps, have it generate a conformance to an `Applicable` protocol like this one, but that's probably overkill:

	protocol Applicable {
		typealias ReturnValue
		typealias ArgumentTuple
		func apply(to: ArgumentTuple) -> ReturnValue
	}

(Actually, as I think about this, I wonder if `Applicable` could give us the `@splatting` property for free: take a generic parameter on Applicable and someone can specify a bare function, but you can't call it directly, only through its `apply(to:)` method.)

2. If `fn` is overloaded, `fn.apply(x)` will end up selecting an `fn` overload based on the type of `x`. Concrete example: `(+).apply(tupleOfInts)` would give you the `Int, Int` implementation of the `+` operator.

3. There's no way to add your own methods to a function type. (At least, I'm not proposing there would be. There's no particular reason we couldn't have other methods on functions, particularly if there's an `Applicable` protocol to extend.)

But `apply` is not a keyword, `apply(to:)` does not receive any special parsing, and you can still splatter `apply`s all around your code with no consequences whatsoever. Honestly, that's the main virtue of the `apply(to:)` suggestion: that there's really very little to it.

-- 
Brent Royal-Gordon
Architechies



More information about the swift-evolution mailing list