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.
let number: Int? = 3
let biggerThan2 = number.filter { $0 > 2 } // .Some(3)
let biggerThan3 = number.filter { $0 > 3 } // .None
let number: Int? = 3
number.mapNil { 2 } // .Some(3)
let nilledNumber: Int? = nil
nilledNumber.mapNil { 2 } // .Some(2)
let number: Int? = 3
number.flatMapNil { .Some(2) } // .Some(3)
let nilledNumber: Int? = nil
nilledNumber.flatMapNil { .Some(2) } // .Some(2)
let number: Int? = 3
number.then { print($0) } // prints "3"
let nilledNumber: Int? = nil
nilledNumber.then { print($0) } // print won't be called
let number: Int? = 3
number.maybe(100) { $0 1 } // 4
let nilledNumber: Int? = nil
nilledNumber.maybe(100) { $0 1 } // 100
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
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
let number: Int? = 3
let isSome = number.isSome // true
let nilledNumber: Int? = nil
let isSome = nilledNumber.isSome // false
let number: Int? = 3
let isSome = number.isNone // false
let nilledNumber: Int? = nil
let isSome = nilledNumber.isNone // true
Carthage:
github "RuiAAPeres/OptionalExtensions"
CocoaPods:
pod "OptionalExtensions"
Manually:
Grab the OptionalExtensions.swift file and drop it in your project.
We will gladly accept Pull Requests with new methods or improving the ones that already exist. Documentation, or tests, are always welcome as well. ❤️
OptionalExtensions is licensed under the MIT License, Version 2.0. View the license file
Copyright (c) 2015 Rui Peres