[swift-evolution] [Pitch/Reality Check] Allow instance members as parameter default values

Slava Pestov spestov at apple.com
Wed Feb 22 19:26:45 CST 2017


I think this is a manifestation of a more general problem, that default arguments cannot capture values from outer scope. Saying they’re evaluated in “type context” and not “instance context” is one way to skirt around the issue, but you can still trigger capturing anyway, and crash in SILGen:

public func foo() {
  let x = 10

  func bar(y: Int = x) {}
}

Fixing this would not be too difficult, just refactoring some code in Sema so that we actually compute the captures of each default argument generator, and then emit the captures when we call one.

Slava

> On Feb 22, 2017, at 10:16 AM, Nate Cook via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Hello all,
> 
> I was surprised to find that I can't use an instance member as the default value of a method parameter, only constants and the run-time calculated #file, #line, etc. Is it possible to remove this limitation?
> 
> I'd like to propose that we add an overload of the collection index(_:offsetBy:) methods that use the collection's startIndex as a default parameter, but we can't provide that without either this feature or an extra overload. If the declaration looks like this:
> 
> extension Collection {
>     func index(_ i: Index = startIndex, offsetBy n: IndexDistance) -> Index {
>         // ...
>     }
> }
> 
> then calling that method with an omitted first parameter would treat it as something like this:
> 
> extension Collection {
>     func index(offsetBy n: IndexDistance) -> Index {	
>         let i = startIndex
>         // ...
>     }
> }
> 
> Is this just syntactic sugar, or am I missing something that makes this harder than it looks? I can see how more complex expressions could be useful there, too, and can't find an obvious reason we couldn't use any code that could be inserted at the top of the method body.
> 
> Thanks!
> Nate
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

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


More information about the swift-evolution mailing list