Swift Sequences are limited in that they don't support Iterators with a throwing next().

Overview

FailableSequence

Swift Sequences are limited in that they don't support Iterators with a throwing next().

There are several use cases for such sequences, for example FileHandles and other data streams can yield an error on each read operation. The FailableSequence module aims to provide support for these use cases.

Swift may in the future have build-in support for failable Sequences. See the discussion on the swift language forums.

Installation

For a Swift Package

Edit the Package.swift file. Add the FailableSequence as a dependency:

let package = Package(
    name: " ... ",
    products: [ ... ],
    dependencies: [
        .package(url: "https://github.com/berikv/FailableSequence.git", from: "0.0.2") // here
    ],
    targets: [
        .target(
            name: " ... ",
            dependencies: [
                "FailableSequence" // and here
            ]),
    ]
)

For .xcodeproj projects

  1. Open menu File > Add Packages...
  2. Search for "https://github.com/berikv/FailableSequence.git" and click Add Package.
  3. Open your project file, select your target in "Targets".
  4. Open Dependencies
  5. Click the + sign
  6. Add FailableSequence

Use the module by importing it in a .swift file:

import FailableSequence

failableSequence(first: 0) { $0 + 1 }

Usage

Create a failable sequence using a first and next().

import FailableSequence

struct DivisionByZero: Error {}

let sequence = failableSequence(first: 10) { element in
    if element == 0 { throw DivisionByZero() }
    return 1 / element
}

do {
    try sequence.forEach { number in
        print(number)
    }
} catch {
    print(error)
}

Create a lazy failable map from another sequence.

let sequence = (0..<4).failableMap { number -> Int in
    if (3 - number) == 0 { throw DivisionByZero() }
    return 1 / (3 - number)
}

do {
    try sequence.forEach { number in
        print(number)
    }
} catch {
    print(error)
}

Create an Array from a FailableSequence.

// Note, if this sequence throws, it would happen on Array init. 
let sequence = (0..<3).failableMap { number -> Int in
    if (3 - number) == 0 { throw DivisionByZero() }
    return 1 / (3 - number)
}

let array = try Array(sequence) // [0, 0, 1]

Note that throwing an error will not end the sequence.

let sequence = (0..<4).failableMap { number -> Int in
    if number == 2 { throw DivisionByZero() }
    return 1 / (2 - number)
}

let array = Array(sequence.skipOnThrowSequence) // [0, 1, -1]

License

Licensed under MIT. See the license.md

You might also like...
Swift Markdown is a Swift package for parsing, building, editing, and analyzing Markdown documents.

Swift Markdown is a Swift package for parsing, building, editing, and analyzing Markdown documents.

Swift-DocC is a documentation compiler for Swift frameworks and packages aimed at making it easy to write and publish great developer documentation.

Swift-DocC is a documentation compiler for Swift frameworks and packages aimed at making it easy to write and publish great developer docum

Cross-Platform, Protocol-Oriented Programming base library to complement the Swift Standard Library. (Pure Swift, Supports Linux)

SwiftFoundation Cross-Platform, Protocol-Oriented Programming base library to complement the Swift Standard Library. Goals Provide a cross-platform in

Swift - ✏️Swift 공부 저장소✏️

Swift 스위프트의 기초 1. Swift의 기본 2. 변수와 상수 [3. 데이터 타입 기본] [4. 데이터 타입 고급] 5. 연산자 6. 흐름 제어 7. 함수 8. 옵셔널 객체지향 프로그래밍과 스위프트 9. 구조체와 클래스 10. 프로퍼티와 메서드 11. 인스턴스 생

Swift-ndi - Swift wrapper around NewTek's NDI SDK

swift-ndi Swift wrapper around NewTek's NDI SDK. Make sure you extracted latest

__.swift is a port of Underscore.js to Swift.

__.swift Now, __.swift is version 0.2.0! With the chain of methods, __.swift became more flexible and extensible. Documentation: http://lotz84.github.

SNTabBarDemo-Swift - Cool TabBar With Swift
SNTabBarDemo-Swift - Cool TabBar With Swift

SNTabBarDemo-Swift Cool TabBar How To Use // MARK: - setup private func setu

Swift-compute-runtime - Swift runtime for Fastly Compute@Edge

swift-compute-runtime Swift runtime for Fastly Compute@Edge Getting Started Crea

Swift-HorizontalPickerView - Customizable horizontal picker view component written in Swift for UIKit/iOS

Horizontal Picker View Customizable horizontal picker view component written in

Owner
Berik Visschers
Berik Visschers
Alert popup to notify your users if they use an unsupported iOS version

UnsupportedOSVersionAlert This source code alerts your users if they use your app with an unsupported version of iOS (e.g. iOS 10.0 beta). The alert l

Josef Moser 8 Mar 11, 2019
BCSwiftTor - Opinionated pure Swift controller for Tor, including full support for Swift 5.5 and Swift Concurrency

BCSwiftTor Opinionated pure Swift controller for Tor, including full support for

Blockchain Commons, LLC — A “not-for-profit” benefit corporation 4 Oct 6, 2022
Swift-when - Expression switch support in Swift

Swift When - supporting switch expressions in Swift! What is it? Basically, it a

Gordan Glavaš 7 Nov 24, 2022
Mechanical editing support for Package.swift manifests

Mechanical editing support for Package.swift manifests. Implements Swift Evolution proposal SE-301

Owen Voorhees 9 Jan 4, 2023
This is a Swift package with support for macOS that allows to start Java Jar's with the default or a custom JVM.

Jar.swift jar runner for macos Jar.swift is created and maintaned with ❥ by Sascha Muellner. What? This is a Swift package with support for macOS that

Swift Package Repository 1 Nov 11, 2021
Support library of BudouX.swift to handle HTML

HTMLBudouX.swift HTMLBudouX.swift is a support library of BudouX.swift to handle HTML. Detail about BudouX.swift is here Usage You can translate an HT

griffin-stewie 1 Dec 31, 2021
Collection of native Swift extensions to boost your development. Support tvOS and watchOS.

SparrowKit Collection of native Swift extensions to boost your development. Support iOS, tvOS and watchOS. If you like the project, don't forget to pu

Ivan Vorobei 119 Dec 20, 2022
macOS utility for converting fat-frameworks to SPM-compatible XCFramework with arm64-simulator support

xcframework-maker macOS utility for converting fat-frameworks to SPM-compatible XCFramework with arm64-simulator support. ?? Description make-xcframew

Dariusz Rybicki 312 Dec 22, 2022
Proper YAML support for Objective-C. Based on recommended libyaml.

YAML.framework for Objective-C Based on C LibYAML library (http://pyyaml.org/wiki/LibYAML) by Kirill Simonov. YAML.framework provides support for YAML

Mirek Rusin 236 Aug 29, 2022
A drop-in `NSComboButton` replacement with pre macOS 13 support.

DSFComboButton A drop-in NSComboButton replacement control with pre macOS 13 support. For when you want to adopt NSComboButton but have to maintain co

Darren Ford 8 Nov 9, 2022