File: foreach.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (40 lines) | stat: -rw-r--r-- 1,422 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// RUN: %target-typecheck-verify-swift

struct IntRange<Int> : Sequence, IteratorProtocol {
  typealias Element = (Int, Int)
  func next() -> (Int, Int)? {}

  typealias Iterator = IntRange<Int>
  func makeIterator() -> IntRange<Int> { return self }
}

func for_each(r: Range<Int>, iir: IntRange<Int>) { // expected-note {{'r' declared here}}
  var sum = 0

  // Simple foreach loop, using the variable in the body
  for i in r {
    sum = sum + i
  }
  // Check scoping of variable introduced with foreach loop
  i = 0 // expected-error{{cannot find 'i' in scope; did you mean 'r'?}}

  // For-each loops with two variables and varying degrees of typedness
  for (i, j) in iir {
    sum = sum + i + j
  }
  for (i, j) in iir {
    sum = sum + i + j
  }
  for (i, j) : (Int, Int) in iir {
    sum = sum + i + j
  }

  // Parse errors
  // FIXME: Bad diagnostics; should be just 'expected 'in' after for-each patter'.
  for i r { // expected-error {{found an unexpected second identifier in constant declaration}}
  }         // expected-note @-1 {{join the identifiers together}}
            // expected-note @-2 {{join the identifiers together with camel-case}}
            // expected-error @-3 {{expected 'in' after for-each pattern}}
            // expected-error @-4 {{expected Sequence expression for for-each loop}}
  for i in r sum = sum + i; // expected-error{{expected '{' to start the body of for-each loop}}
}