Dollar is a Swift library that provides useful functional programming helper methods without extending any built in objects. It is similar to Lo-Dash or Underscore.js in Javascript.
Cent is a library that extends certain Swift object types using the extension feature and gives its two cents to Swift language. It is now moved into a separate repo to support Swift Package Manager
NOTE: Starting Swift 4 $
is no longer a valid identifier. So you get the following error: '$' is not an identifier; use backticks to escape it
. Instead use Dollar
.
Using cocoapods version 0.36.x or greater
Add pod 'Dollar'
to your Podfile
and run pod install
. Add use_frameworks!
to the end of the Podfile
. Also checkout this sample app.
Using Swift Package Manager
Add the following dependency .Package(url: "https://github.com/ankurp/Dollar", majorVersion: 7, minor: 1)
to your Package.swift
file and then run swift build
. Requires swift version 2.2 or greater that you can install from https://swift.org
- If you are using git then add Dollar as a submodule using
git submodule add https://github.com/ankurp/Dollar.git
. If not using git download the project usinggit clone https://github.com/ankurp/Dollar.git
in your project folder. - Open the
Dollar
folder. Drag Dollar.xcodeproj, inside the Dollar folder, into the file navigator of your Xcode project. - In Xcode, navigate to the target configuration window by clicking on the blue project icon, and selecting the application target under the "Targets" heading in the sidebar.
- In the tab bar at the top of that window, open the "Build Phases" panel.
- Expand the "Link Binary with Libraries" group, and add Dollar.framework.
- In your project file
import Dollar
and you can call all of the helper functions.
Still stuck. Then checkout this screencast on how to import
- For Xcode 15 (Swift 5.1) use version
10.0.0
- For Xcode 11 (Swift 5.0) use version
9.0.0
- For Xcode 10 (Swift 4.2) use version
8.0.0
- For Xcode 9 (Swift 4) use version
7.1.0
- For Xcode 8 (Swift 3) use version
6.0.0
- For Xcode 7 (Swift 2) use version
4.1.0
or5.2.0
- For Xcode 6.3 (Swift 1.2) use version
3.0.3
- For Xcode 6.1 and 6.2 (Swift 1.1) use version
2.2.0
- Using
Cocoa Pods
- Using
Swift Package Manager
- Using
git submodule
- If you need help, use gitter.im or post a question on Stack Overflow with tag
dollar.swift
. - If you'd like to ask a general question, use Stack Overflow.
- If you found a bug, open an issue.
- If you have a feature request, open an issue.
- If you want to contribute, submit a pull request.
Creates an array of elements from the specified indexes, or keys, of the collection. Indexes may be specified as individual arguments or as arrays of indexes.
Dollar.at(["ant", "bat", "cat", "dog", "egg"], indexes: 0, 2, 4)
=> ["ant", "cat", "egg"]
Creates an array of elements split into groups the length of size. If array can’t be split evenly, the final chunk will be the remaining elements.
Dollar.chunk([1, 2, 3, 4], size: 2)
=> [[1, 2], [3, 4]]
Dollar.chunk([1, 2, 3, 4], size: 3)
=> [[1, 2, 3], [4]]
Creates an array with all nil values removed.
Dollar.compact([3, nil, 4, 5])
=> [3, 4, 5]
Dollar.compact([nil, nil]) as NSObject[]
=> []
Checks if a given value is present in the array.
Dollar.contains([1, 2, 3, 1, 2, 3], value: 2)
=> true
Dollar.contains([1, 2, 3, 1, 2, 3], value: 10)
=> false
Cycles through the array definetly or indefinetly passing each element into the callback function. The second parameter is to specify how many times to cycle through the array. If left out it will cycle indefinetly.
Dollar.cycle([1, 2, 3], 2) {
print($0)
}
// Prints the following
123123
Creates an array excluding all values of the provided arrays
Dollar.difference([1, 2, 3, 4, 5], [5, 2, 10])
=> [1, 3, 4]
Passes each element in the array to the callback
Dollar.each(["A", "B"]) {
print("Value \($0)")
}
=> ["A", "B"]
Dollar.each(["A", "B"]) { (index, elem) in
print("\(index) - \(elem)")
}
=> ["0 - A", "1 - B"]
Checks if the given callback returns true value for all items in the array.
Dollar.every([1, 2, 3, 4], callback: { $0 < 20 })
=> true
Dollar.every([1, 2, 3, 4]) { $0 == 1 }
=> false
Returns factorial of integer
Dollar.factorial(3)
=> 6
Dollar.factorial(0)
=> 1
Get element from an array at the given index which can be negative to find elements from the end of the array. A default value can be returned if indexing out of bounds.
let arr = [1, 2, 3, 4, 5, 6, 7, 8]
Dollar.fetch(arr, 100)
=> nil
Dollar.fetch(arr, 100, orElse: 42)
=> 42
Dollar.fetch(arr, -1)
=> 8
Fills elements of array with value from start up to, but not including, end. This method mutates array.
var arr = Array<Int>(count: 5, repeatedValue: 1)
Dollar.fill(&arr, withElem: 42)
=> [42, 42, 42, 42, 42]
var arr = Array<Int>(count: 5, repeatedValue: 1)
Dollar.fill(&arr, withElem: 42, startIndex: 1, endIndex: 3)
=> [1, 42, 42, 42, 1]
Iterates over elements of an array and returning the first element that the callback returns true for.
Dollar.find([1, 2, 3, 4], callback: { $0 == 2 })
=> 2
Dollar.find([1, 2, 3, 4]) { $0 == 10 }
=> nil
This method is like find except that it returns the index of the first element that passes the callback check.
let arr = [["age": 36], ["age": 40], ["age": 1]]
let result = Dollar.findIndex(arr) { $0["age"] < 20 }
result
=> 2
This method is like findIndex except that it iterates over elements of the array from right to left.
let arr = [["age": 36], ["age": 40], ["age": 1]]
let result = Dollar.findLastIndex(arr) { $0["age"] > 30 }
result
=> 1
Gets the first element in the array.
Dollar.first([1, 2, 3, 4])
=> 1
Dollar.first([])
=> nil
This method returns a dictionary of values grouped by the value returned by a callback.
Dollar.groupBy([1, 2, 3, 4, 5], callback: {$0 % 2})
=> [0: [2, 4], 1: [1, 3]]
Dollar.groupBy(["strings", "with", "different", lengths"], callback: {$0.characters.count})
=> [7: ["strings", "lengths"], 9: ["different"], 4: ["With"]]
Gets the second element in the array.
Dollar.second([1, 2, 3, 4])
=> 2
Dollar.second([1])
=> nil
Dollar.second([])
=> nil
Maps a function that converts elements to a list and then concatenates them.
let values = [2, 3, 4, 5, 6, 7]
Dollar.flatMap(values) { [$0, $0] }
=> [2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7]
Maps a function that converts a type to an Optional over an Optional, and then returns a single-level Optional.
let url = NSURL(string: "https://apple.com/swift")
Dollar.flatMap(url) { $0.lastPathComponent }
=> Optional("swift")
Note: This is the same behavior as Optional chaining. The code above translates to
NSURL(string: "https://apple.com/swift/")?.lastPathComponent
=> Optional("swift")
Flattens a nested array of any depth.
Dollar.flatten([[3], 4, 5]) as Int[]
=> [3, 4, 5]
Dollar.flatten([[3], "Hello", 5]) as NSObject[]
=> [3, "Hello", 5]
Dollar.flatten([[[3], 4], 5]) as Int[]
=> [3, 4, 5]
This method returns a dictionary of values in an array mapping to the total number of occurrences in the array. If passed a function it returns a frequency table of the results of the given function on the arrays elements.
Dollar.frequencies(["a", "a", "b", "c", "a", "b"])
=> ["a": 3, "b": 2, "c": 1]
Dollar.frequencies([1, 2, 3, 4, 5]) { $0 % 2 == 0 }
=> [false: 3, true: 2]
GCD function return greatest common denominator with number passed
Dollar.gcd(3, 10)
=> 1
Dollar.gcd(3, 9)
=> 3
Gets the index at which the first occurrence of value is found.
Dollar.indexOf([1, 2, 3, 1, 2, 3], value: 2)
=> 1
Dollar.indexOf(["A", "B", "C"], value: "B")
=> 1
Dollar.indexOf([3, 4, 5], value: 5)
=> 2
Dollar.indexOf([3, 4, 5], value: 3)
=> 0
Dollar.indexOf([3, 4, 5], value: 2)
=> nil
Gets all but the last element or last n elements of an array.
Dollar.initial([3, 4, 5])
=> [3, 4]
Dollar.initial([3, 4, 5], numElements: 2)
=> [3]
Creates an array of unique values present in all provided arrays.
Dollar.intersection([1, 2, 3], [5, 2, 1, 4], [2, 1])
=> [1, 2]
Returns true if i is in interval or range
Dollar.it("c", isIn: "a"..."z")
=> true
Dollar.it("z", isIn: "a"..<"z")
=> false
Dollar.it(1, isIn: -1.0...10.0)
=> true
Gets the last element from the array.
Dollar.last([3, 4, 5])
=> 5
Gets the index at which the last occurrence of value is found.
Dollar.lastIndexOf([1, 2, 3, 1, 2, 3], value: 2)
=> 4
LCM method return least common multiple with number passed
Dollar.lcm(3, 10)
=> 30
Dollar.lcm(3, 9)
=> 9
The opposite of initial this method gets all but the first element or first n elements of an array.
Dollar.rest([3, 4, 5])
=> [4, 5]
Dollar.rest([3, 4, 5], numElements: 2)
=> [5]
Maps each element to new value based on the map function passed
Dollar.map([1, 2, 3, 4]) {
$0 * 2
}
=> [2, 4, 6, 8]
Retrieves the minimum value in an array.
Dollar.min([2, 1, 2, 3, 4])
=> 1
Retrieves the maximum value in an array.
Dollar.max([1, 2, 3, 4, 2, 1])
=> 4
Retrieves the value of a specified property from all elements in the array.
let arr = [["age": 20], ["age": 30], ["age": 40]]
Dollar.pluck(arr, value: "age")
=> [20, 30, 40]
Removes all provided values from the given array.
Dollar.pull([3, 4, 5, 3, 5], values: 3, 5)
=> [4]
Dollar.pull([3, 4, 5, 3, 5], values: 4)
=> [3, 5, 3, 5]
Dollar.pull([3, 4, 5, 3, 5], values: 3, 4, 5)
=> []
Removes all provided values from the given array at the given indices
let arr = [10, 20, 30, 40, 50]
Dollar.pullAt(arr, indices: 1, 2, 3)
Creates an array of numbers (positive and/or negative) progressing from start up to but not including end.
Dollar.range(4)
=> [0, 1, 2, 3]
Dollar.range(from: 1, to: 5)
=> [1, 2, 3, 4]
Dollar.range(from: 0, to: 20, incrementBy: 5)
=> [0, 5, 10, 15]
Dollar.range(from: 1, through: 5)
=> [1, 2, 3, 4, 5]
Dollar.range(from: 0, through: 20, incrementBy: 5)
=> [0, 5, 10, 15, 20]
Reduce function that will resolve to one value after performing combine function on all elements
Dollar.reduce([1, 2, 3], initial: 0) { (total, element) in
total + element
}
=> 6
Returns a sample item from the array
let arr: [Int] = [2, 1, 2, 3, 4]
Dollar.contains(arr, value: Dollar.sample(arr))
=> true
Creates an array of an arbitrary sequence. Especially useful with builtin ranges.
Dollar.sequence(0..4)
=> [0, 1, 2, 3]
Dollar.sequence(-2.0..2.0)
=> [-2.0, -1.0, 0.0, 1.0]
Dollar.sequence((0..20).by(5))
=> [0, 5, 10, 15]
Dollar.sequence("abc")
=> ["a", "b", "c"]
Removes an element from array.
Dollar.remove(["A", "B", "C", "D"], value: "B")
=> ["A", "C", "D"]
Removes all elements from an array that the callback
returns true.
let result = Dollar.remove([1, 2, 3, 4, 5, 6]) {
$0 == 2 || $0 == 3
}
result
=> [1, 4, 5, 6]
Shuffles and returns the new shuffled array
let result = Dollar.shuffle([1, 2, 3, 4, 5, 6])
result
=> [4, 1, 3, 5, 6, 2]
Returns size of the array
Dollar.size(["a", "b", "c")
=> 3
Gives the smallest index at which a value should be inserted into a given the array is sorted.
Dollar.sortedIndex([3, 4, 6, 10], value: 5)
=> 2
Dollar.sortedIndex([10, 20, 30, 50], value: 40)
=> 3
Creates a tranposed matrix.
Dollar.transpose([[1, 2, 3], [4, 5, 6]])
=> [[1, 4], [2, 5], [3, 6]]
Creates an array of unique values, in order, of the provided arrays.
Dollar.union([1, 2, 3], [5, 2, 1, 4], [2, 1])
=> [1, 2, 3, 5, 4]
Creates an array of all values, including duplicates, of the arrays in the order they are provided.
let arr = [1, 5]
let arr2 = [2, 4]
let arr3 = [5, 6]
let result = Dollar.merge(arr, arr2, arr3)
result
=> [1, 5, 2, 4, 5, 6]
Creates a duplicate-value-free version of an array.
Dollar.uniq([1, 2, 1, 3, 1])
=> [1, 2, 3]
Dollar.uniq([1, 2.5, 3, 1.5, 2, 3.5]) {
floor($0)
}
=> [1, 2.5, 3]
Creates an array excluding all provided values.
Dollar.without([3, 4, 5, 3, 5], values: 3, 5)
=> [4]
Dollar.without([3, 4, 5, 3, 5], values: 4)
=> [3, 5, 3, 5]
Dollar.without([3, 4, 5, 3, 5], values: 3, 4, 5)
=> []
Creates an array that is the symmetric difference of the provided arrays.
Dollar.xor([1, 2, 3], [5, 2, 1, 4])
=> [3, 4, 5]
Creates an array of grouped elements, the first of which contains the first elements of the given arrays.
Dollar.zip(["fred", "barney"], [30, 40], [true, false]) as [NSObject]
=> [["fred", 30, true], ["barney", 40, false]]
Creates an object composed from arrays of keys and values.
Dollar.zipObject(["fred", "barney"], values: [30, 40])
=> ["fred": 30, "barney": 40]
Produces an array of arrays, each containing n elements, each offset by step. Stops after a partition is less than n length.
let arr = [1, 2, 3, 4, 5]
Dollar.partition(arr, n: 2)
=> [[1, 2], [3, 4]]
Dollar.partition(arr, n: 4, step: 1)
=> [[1, 2, 3, 4], [2, 3, 4, 5]]
Dollar.partition(arr, n: 4, step: 1, pad: nil)
=> [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5]]
Dollar.partition(arr, n: 4, step: 1, pad: [6, 7, 8])
=> [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]]
Produces an array of arrays, each containing n elements, each offset by step. Continues after a partition is less than n length.