Files
swift-mirror/test/expr/closure/single_expr.swift
Doug Gregor ce3fe3ae92 Implement Ruby-inspired closure syntax.
This commit implements closure syntax that places the (optional)
parameter list in pipes within the curly braces of a closure. This
syntax "slides" well from very simple closures with anonymous
arguments, e.g.,

  sort(array, {$1 > $0})

to naming the arguments

  sort(array, {|x, y| x > y})

to adding a return type and/or parameter types

  sort(array, {|x : String, y : String| -> Bool x > y})

and with multiple statements in the body:

  sort(array, {|x, y|
    print("Comparing \(x) and \(y)\n")
    return x > y
  })

When the body contains only a single expression, that expression
participates in type inference with its enclosing expression, which
allows one to type-check, e.g.,

  map(strings, {|x| x.toUpper()})

without context. If one has multiple statements, however, one will
need to provide additional type information either with context

  strings = map(strings, {
    return $0.toUpper()
  })

or via annotations

  map(strings, {|x| -> String 
    return x.toUpper()
  }

because we don't perform inter-statement type inference.

The new closure expressions are only available with the new type
checker, where they completely displace the existing { $0 + $1 }
anonymous closures. 'func' expressions remain unchanged.

The tiny test changes (in SIL output and the constraint-checker test)
are due to the PipeClosureExpr AST storing anonymous closure arguments
($0, $1, etc.) within a pattern in the AST. It's far cleaner to
implement this way.

The testing here is still fairly light. In particular, we need better
testing of parser recovery, name lookup for closures with local types,
more deduction scenarios, and multi-statement closures (which don't
get exercised beyond the unit tests).



Swift SVN r5169
2013-05-14 05:17:10 +00:00

21 lines
522 B
Swift

// RUN: %swift -parse %s -verify
func takeIntToInt(f : (Int) -> Int) { }
func takeIntIntToInt(f : (Int, Int) -> Int) { }
// Simple closures with anonymous arguments
func simple() {
takeIntToInt({$0 + 1})
takeIntIntToInt({$0 + $1 + 1})
}
// Anonymous arguments with inference
func myMap<T, U>(array : T[], f : (T) -> U) -> U[] {}
func testMap(array : Int[]) {
var farray = myMap(array, { Float($0) as Float })
var f : Float = farray[0]
var farray2 = myMap(array, { |x : Int | Float(x) })
farray = farray2
}