Swift µframework with extensions for the Optional Type

Overview

OptionalExtensions

CocoaPods Swift 4.0 License MIT

Why?

Swift's Optional is pretty awesome, but it can always get better. This repository is an humble attempt to add some utility methods to it.

Operators

filter: (Wrapped -> Bool) -> Optional<Wrapped>

let number: Int? = 3

let biggerThan2 = number.filter { $0 > 2 } // .Some(3)

let biggerThan3 = number.filter { $0 > 3 } // .None

mapNil: (Void -> Wrapped) -> Optional<Wrapped>

let number: Int? = 3
number.mapNil { 2 } // .Some(3)

let nilledNumber: Int? = nil
nilledNumber.mapNil { 2 } // .Some(2)

flatMapNil: (Void -> Optional<Wrapped>) -> Optional<Wrapped>

let number: Int? = 3
number.flatMapNil { .Some(2) } // .Some(3)

let nilledNumber: Int? = nil
nilledNumber.flatMapNil { .Some(2) } // .Some(2)

then: (Wrapped -> Void) -> Void (similar to [T]'s forEach)

let number: Int? = 3
number.then { print($0) } // prints "3"

let nilledNumber: Int? = nil
nilledNumber.then { print($0) } // print won't be called

maybe: U -> (Wrapped -> U) -> U (similar to Haskell's maybe)

let number: Int? = 3
number.maybe(100) { $0 + 1 } // 4

let nilledNumber: Int? = nil
nilledNumber.maybe(100) { $0 + 1 } // 100

onSome: (Wrapped -> Void) -> Optional<Wrapped> (injects a side effect in the .Some branch)

let number: Int? = 3
let sameNumber = number.onSome { print($0) } // prints "3" & returns .Some(3)

let nilledNumber: Int? = nil
let sameNilledNumber = nilledNumber.onSome { print($0) } // .None

onNone: (Void -> Void) -> Optional<Wrapped> (injects a side effect in the .None branch)

let number: Int? = 3
let sameNumber = number.onNone { print("Hello World") } // .Some(3)

let nilledNumber: Int? = nil
let sameNilledNumber = nilledNumber.onNone { print("Hello World") } // prints "Hello World" & returns .None

isSome: Bool

let number: Int? = 3
let isSome = number.isSome // true

let nilledNumber: Int? = nil
let isSome = nilledNumber.isSome // false

isNone: Bool

let number: Int? = 3
let isSome = number.isNone // false

let nilledNumber: Int? = nil
let isSome = nilledNumber.isNone // true

Setup

Carthage:

github "RuiAAPeres/OptionalExtensions"

CocoaPods:

pod "OptionalExtensions"

Manually:

Grab the OptionalExtensions.swift file and drop it in your project.

Contributing

We will gladly accept Pull Requests with new methods or improving the ones that already exist. Documentation, or tests, are always welcome as well. ❤️

License

OptionalExtensions is licensed under the MIT License, Version 2.0. View the license file

Copyright (c) 2015 Rui Peres

Comments
  • Sugary syntax version

    Sugary syntax version

    This is not an issue!

    I'm just interested in your opinion of the code below, it adds no additional functionality, hence, not an issue. As an exercise for my own entertainment, I've created a version of the extension that utilises as much sugary syntax as I could muster (using single expressions per function and using if case syntax when apt, etc).

    Your original is written in a clear, explicit style which is easy to decipher, the version below is undoubtedly more cryptic (one thing I do like is that each function contains one expression and one return statement, but it is arguable how important that is). I think the versions of onSome and onNone would fit with the current style, but the others are a bit of a departure.

    Anyway, I thought I'd throw it out there to see what you thought.

    All the best, Al

    
    public extension Optional {
        func filter(@noescape predicate: Wrapped -> Bool) -> Optional {
            return map(predicate) == .Some(true) ? self : .None
        }
    
        func replaceNil(with replacement: Wrapped) -> Optional {
            return self ?? replacement
        }
    
        func apply(@noescape f: Wrapped -> Void) {
            if case let wrapped? = self { f(wrapped) }
        }
    
        func onSome(@noescape f: Wrapped -> Void) -> Optional {
            apply(f)
            return self
        }
    
        func onNone(@noescape f: Void -> Void) -> Optional {
            if isNone { f() }
            return self
        }
    
        var isSome: Bool {
            return map { _ in true } ?? false
        }
    
        var isNone: Bool {
            return !isSome
        }
    }
    
    enhancement 
    opened by alskipp 16
  • Refactoring tests for better readability

    Refactoring tests for better readability

    I use tests as to understand what a project does - this is a refactor to make that understanding easier.

    Using the given / when / then naming convention, as well as (when possible) one assert per test.

    After doing this refactor, reading over the tests gives me a good idea of what the extensions do. (and on that note I'm wondering if "maybe" expresses what it does... but yet to find a better name):

    screen shot 2016-01-12 at 11 08 37

    opened by gergelyorosz 7
  • Lower deployment requirements

    Lower deployment requirements

    Hey!

    Optional extensions look great, thank you for them!

    This PR lowers deployment targets to following:

    • iOS 8
    • OS X 10.10
    • tvOS 9.0
    • watchOS 2.0

    There does not seem any particular reason not to support those.

    opened by DenTelezhkin 1
  • Added tests

    Added tests

    I wanted to get the tests working using just one Xcode scheme, but struggled to get that working 😕 The OptionalExtensionsTests scheme has been made public, so it should work as expected.

    opened by alskipp 0
  • Adds ReadMe examples as HeaderDocs

    Adds ReadMe examples as HeaderDocs

    I found this convenient to have the examples ready to hand, especially before I wrapped my head around it.

    I also added a compactMapNil for iOS 9.3+, if you like that.

    opened by AmitaiB 0
Owner
Rui Peres
Software Engineer 🛠 | Ultra Trail Runner 🏃‍♂️🏔 "Technology as a means to an end 🚀"
Rui Peres
A functional utility belt implemented as Swift 2.0 protocol extensions.

Oriole [![CI Status](http://img.shields.io/travis/Tyler Thompson/Oriole.svg?style=flat)](https://travis-ci.org/Tyler Thompson/Oriole) Oriole is a set

Tyler Paul Thompson 11 Aug 10, 2019
A set of Swift extensions for standard types and classes.

ExSwift Set of Swift extensions for standard types and classes. Installation Because of Xcode errors it's not possible to integrate this project with

Pierluigi D'Andrea 3.4k Dec 27, 2022
Functional chaining and promises in Swift

Forbind Functional chaining and promises in Swift Note: still in an experimental state. Everything could change. I would love some feedback on this. W

Ulrik Flænø Damm 45 Sep 1, 2022
Functional programming tools and experiments in Swift.

Funky The documentation (courtesy of realm/jazzy) is available here: https://brynbellomy.github.io/Funky Master branch is currently compatible with: S

Bryn Bellomy 12 May 2, 2017
Collection of must-have functional Swift tools

NOTE: This project has been merged with and superceded by Rob Rix's Result µframework. LlamaKit Collection of must-have functional tools. Trying to be

null 619 Aug 5, 2022
Functional programming in Swift

Swiftz Swiftz is a Swift library for functional programming. It defines functional data structures, functions, idioms, and extensions that augment the

TypeLift 3.3k Dec 25, 2022
Functional JSON parsing library for Swift

Argo Argo is a library that lets you extract models from JSON or similar structures in a way that's concise, type-safe, and easy to extend. Using Argo

thoughtbot, inc. 3.5k Jan 7, 2023
Infix operators for monadic functions in Swift

Indecipherable symbols that some people claim have actual meaning. Please see the documentation for installation instructions. What's included? Import

thoughtbot, inc. 825 Dec 7, 2022
🏹 Bow is a cross-platform library for Typed Functional Programming in Swift

Bow is a cross-platform library for Typed Functional Programming in Swift. Documentation All documentation and API reference is published in our websi

Bow 613 Dec 20, 2022
Functional programming in Swift

Swiftz Swiftz is a Swift library for functional programming. It defines functional data structures, functions, idioms, and extensions that augment the

TypeLift 3.3k Jan 6, 2023
UISlider clone with multiple thumbs and values, range highlight, optional snap intervals, optional value labels, either vertical or horizontal.

MultiSlider UISlider clone with multiple thumbs and values, range highlight, optional snap intervals, optional value labels, either vertical or horizo

Yonat Sharon 326 Dec 29, 2022
UISlider clone with multiple thumbs and values, range highlight, optional snap intervals, optional value labels, either vertical or horizontal.

MultiSlider UISlider clone with multiple thumbs and values, range highlight, optional snap intervals, optional value labels, either vertical or horizo

Yonat Sharon 326 Dec 29, 2022
A μframework of extensions for SequenceType in Swift 2.0, inspired by Python's itertools, Haskell's standard library, and other things.

SwiftSequence Full reference here. (If you're looking for data structures in Swift, those have been moved to here) SwiftSequence is a lightweight fram

Donnacha Oisín Kidney 376 Oct 12, 2022
Type-safe networking abstraction layer that associates request type with response type.

APIKit APIKit is a type-safe networking abstraction layer that associates request type with response type. // SearchRepositoriesRequest conforms to Re

Yosuke Ishikawa 1.9k Dec 30, 2022
A phantom type is a custom type that has one or more unused type parameters.

PhantomTypes A phantom type is a custom type that has one or more unused type parameters. Phantom types allow you to enforce type-safety without sacri

null 3 Nov 4, 2022
Swift µframework of simple functional programming tools

Prelude This is a Swift µframework providing a number of simple functions that I use in many of my other frameworks. Rather than continue to reimpleme

Rob Rix 405 Jun 29, 2022
Swift µframework providing Future

Future [] (https://github.com/Carthage/Carthage) Swift µframework providing Future<T, Error>. This library is inspired by the talk of Javier Soto at S

Le Van Nghia 122 Jun 3, 2021
Corridor A Coreader-like Dependency Injection μFramework

Corridor A Coreader-like Dependency Injection μFramework Table of Contents Why | Examples | Usage | Installation | Credits & License | Why In order to

symentis GmbH 60 Nov 1, 2022
µframework for Attributed strings.

Attributed µframework for Attributed strings. What is Attributed? Attributed aims to be a drop in replacement to the current version of the NSAttribut

Nicholas Maccharoli 754 Jan 9, 2023
A µFramework for showing alerts like the one used when copying from pasteboard or connecting Apple pencil

Drops ?? A µFramework for showing alerts like the one used when copying from pasteboard or connecting Apple pencil. Features iOS 10+ Can be used in Sw

Omar Albeik 709 Dec 29, 2022