<!--
{
  "availability" : [
    "iOS: 8.0.0 -",
    "iPadOS: 8.0.0 -",
    "macCatalyst: 13.0.0 -",
    "macOS: 10.10.0 -",
    "tvOS: 9.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 2.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Swift",
  "identifier" : "/documentation/Swift/AnyIterator/init(_:)-5l6js",
  "metadataVersion" : "0.1.0",
  "role" : "Initializer",
  "symbol" : {
    "kind" : "Initializer",
    "modules" : [
      "Swift"
    ],
    "preciseIdentifier" : "s:s11AnyIteratorVyAByxGxSgyccfc"
  },
  "title" : "init(_:)"
}
-->

# init(_:)

Creates an iterator that wraps the given closure in its `next()` method.

```
init(_ body: @escaping () -> Element?)
```

## Parameters

`body`

A closure that returns an optional element. `body` is
executed each time the `next()` method is called on the resulting
iterator.

## Discussion

The following example creates an iterator that counts up from the initial
value of an integer `x` to 15:

```
var x = 7
let iterator: AnyIterator<Int> = AnyIterator {
    defer { x += 1 }
    return x < 15 ? x : nil
}
let a = Array(iterator)
// a == [7, 8, 9, 10, 11, 12, 13, 14]
```

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)