Skip to content

RuiAAPeres/OptionalExtensions

Repository files navigation

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