Dollar

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
.
Setup
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
Using git submodule
- 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
Support for Xcode and Swift
- 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
Demo Apps
- Using
Cocoa Pods
- Using
Swift Package Manager
- Using
git submodule
Communication
- 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.
Dollar Usage
Array
at - Dollar.at
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.
chunk - Dollar.chunk
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.
compact - Dollar.compact
Creates an array with all nil values removed.
contains - Dollar.contains
Checks if a given value is present in the array.
cycle - Dollar.cycle
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.
difference - Dollar.difference
Creates an array excluding all values of the provided arrays
each - Dollar.each
Passes each element in the array to the callback
every - Dollar.every
Checks if the given callback returns true value for all items in the array.
factorial Dollar.factorial
Returns factorial of integer
fetch - Dollar.fetch
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.
fill - Dollar.fill
Fills elements of array with value from start up to, but not including, end. This method mutates array.
find - Dollar.find
Iterates over elements of an array and returning the first element that the callback returns true for.
findIndex - Dollar.findIndex
This method is like find except that it returns the index of the first element that passes the callback check.
findLastIndex - Dollar.findLastIndex
This method is like findIndex except that it iterates over elements of the array from right to left.
first - Dollar.first(array: AnyObject[])
Gets the first element in the array.
groupBy Dollar.groupBy
This method returns a dictionary of values grouped by the value returned by a callback.
second - Dollar.second(array: AnyObject[])
Gets the second element in the array.
flatMap - Dollar.flatMap
Maps a function that converts elements to a list and then concatenates them.
flatMap - Dollar.flatMap
Maps a function that converts a type to an Optional over an Optional, and then returns a single-level Optional.
Note: This is the same behavior as Optional chaining.
The code above translates to
flatten - Dollar.flatten
Flattens a nested array of any depth.
frequencies - Dollar.frequencies
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.
gcd Dollar.gcd
GCD function return greatest common denominator with number passed
indexOf - Dollar.indexOf
Gets the index at which the first occurrence of value is found.
initial - Dollar.initial
Gets all but the last element or last n elements of an array.
intersection - Dollar.intersection
Creates an array of unique values present in all provided arrays.
it-isIn Dollar.it<T: Comparable>(i: T, isIn range: Range<T>)
Returns true if i is in interval or range
last - Dollar.last
Gets the last element from the array.
lastIndexOf - Dollar.lastIndexOf
Gets the index at which the last occurrence of value is found.
lcm Dollar.lcm
LCM method return least common multiple with number passed
rest - Dollar.rest
The opposite of initial this method gets all but the first element or first n elements of an array.
map - Dollar.map
Maps each element to new value based on the map function passed
min - Dollar.min
Retrieves the minimum value in an array.
max - Dollar.max
Retrieves the maximum value in an array.
pluck - Dollar.pluck
Retrieves the value of a specified property from all elements in the array.
pull - Dollar.pull
Removes all provided values from the given array.
pullAt - Dollar.pullAt
Removes all provided values from the given array at the given indices
range - Dollar.range
Creates an array of numbers (positive and/or negative) progressing from start up to but not including end.
reduce - Dollar.reduce
Reduce function that will resolve to one value after performing combine function on all elements
sample - Dollar.sample
Returns a sample item from the array
sequence - Dollar.sequence
Creates an array of an arbitrary sequence. Especially useful with builtin ranges.
remove - Dollar.remove
Removes an element from array.
remove - Dollar.remove
Removes all elements from an array that the callback
returns true.
shuffle - Dollar.shuffle
Shuffles and returns the new shuffled array
size - Dollar.size
Returns size of the array
sortedIndex - Dollar.sortedIndex
Gives the smallest index at which a value should be inserted into a given the array is sorted.
transpose - Dollar.transpose
Creates a tranposed matrix.
union - Dollar.union
Creates an array of unique values, in order, of the provided arrays.
merge - Dollar.merge
Creates an array of all values, including duplicates, of the arrays in the order they are provided.
uniq - Dollar.uniq
Creates a duplicate-value-free version of an array.
without - Dollar.without
Creates an array excluding all provided values.
xor - Dollar.xor
Creates an array that is the symmetric difference of the provided arrays.
zip - Dollar.zip
Creates an array of grouped elements, the first of which contains the first elements of the given arrays.
zipObject - Dollar.zipObject
Creates an object composed from arrays of keys and values.
partition - Dollar.partition
Produces an array of arrays, each containing n elements, each offset by step. Stops after a partition is less than n length.
partitionAll - Dollar.partitionAll
Produces an array of arrays, each containing n elements, each offset by step. Continues after a partition is less than n length.
partitionBy - Dollar.partitionBy
Applies a function to each element in array, splitting it each time the function returns a new value.
Dictionary
keys - Dollar.keys
Creates an array of keys given a dictionary.
values - Dollar.values
Creates an array of values given a dictionary
merge - Dollar.merge
Merges all of the dictionaries together and the latter dictionary overrides the value at a given key
pick - Dollar.pick
Creates a shallow clone of a dictionary composed of the specified keys.
omit - Dollar.omit
Creates a shallow clone of a dictionary excluding the specified keys.
Object
tap - Dollar.tap
Invokes interceptor with the object and then returns object.
Function
after - Dollar.after
Creates a function that executes passed function only after being called n times.
bind - Dollar.bind
Creates a function that, when called, invokes func with the binding of arguments provided.
compose - Dollar.compose
Compose two or more functions where the return value of the first function is passed into the next function. Useful when chaining functions and returns a function that can be called with variadic argument values or an array of values as input
curry - Dollar.curry
Returns a function which when invoked either executes the function returning its result, if all function arguments have been provided, or returns another function that accepts one more argument of the remaining function arguments until all arguments are supplied. This is useful for making partial function as seen in these examples.
id - Dollar.id
The identify function which simply returns the argument its given.
memoize - Dollar.memoize
Returns a memoized function to improve performance by caching recursive function values.
noop - Dollar.noop
A no-operation function.
now - Dollar.now
Gets the number of seconds that have elapsed since the Unix epoch (1 January 1970 00:00:00 UTC).
once - Dollar.once
Get a wrapper function that executes the passed function only once. Useful for getting shared config or creating singleton objects.
partial - Dollar.partial
Creates a function that, when called, invokes func with any additional partial arguments prepended to those provided to the new function.
times - Dollar.times
Call a function n times and also passes the index. If a value is returned in the function then the times method will return an array of those values.
Chaining
Dollar.chain(...)
any
Returns true if callback function returns true for at least one element in the array
all
Returns true if callback function returns true for all elements in the array
each
Passes each element value to the callback function
filter
Filters the arrary to elements for which the callback function returns true
first
Returns the first element in the array and terminates the chain
second
Returns the second element in the array and terminates the chain
third
Returns the third element in the array and terminates the chain
flatten
Flattens a nested array of any depth.
initial
Gets all but the last element or last n elements of an array.
map
Maps each element to the new value returned in the callback function
size
Returns size of the array and terminates the chain
slice
Slices the array based on the start and end position. If an end position is not specified it will slice till the end of the array.
value
Returns the value after evaluating all callbacks
Chaining more than one method
Cent Usage
Array Extensions
<< elem: Element -> [Element]
Overloaded operator to append element to an array or append elements from another array into the first array. Return array with the element appended in the end.
at(indexes: Int...) -> [Element]
Creates an array of elements from the specified indexes, or keys, of the collection.
each(callback: (Element) -> ()) -> [Element]
For each item in the array invoke the callback by passing the elem
eachWithIndex(callback: (Int, Element) -> ()) -> [Element]
For each item in the array invoke the callback by passing the elem along with the index
cycle<U>(times: Int, callback: (Element) -> U)
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.
every(callback: (Element) -> Bool) -> Bool
Checks if the given callback returns true value for all items in the array.
indexOf<T: Equatable>(value: T) -> Int
Gets the index at which the first occurrence of value is found.
fetch(index: Int, orElse: T? = .None) -> T!
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.
findIndex(callback: (Element) -> Bool) -> Int?
This method is like find except that it returns the index of the first element that passes the callback check.
findLastIndex(callback: (Element) -> Bool) -> Int?
This method is like findIndex except that it iterates over elements of the array from right to left.
first() -> Element?
Gets the first element in the array.
flatten() -> [Element]
Flattens a nested array of any depth.
get(index: Int) -> Element?
Get element at index
initial(numElements: Int? = 1) -> [Element]
Gets all but the last element or last n elements of an array.
last() -> Element?
Gets the last element from the array.
rest(numElements: Int? = 1) -> [Element]
The opposite of initial this method gets all but the first element or first n elements of an array.
min<T: Comparable>() -> T?
Retrieves the minimum value in an array.
max<T: Comparable>() -> T?
Retrieves the maximum value in an array.
remove<T: Equatable>(value: T) -> T?
Remove element from array
contains<T:Equatable>(value: T) -> Bool
Checks if a given value is present in the array.
Character Extensions
"A".description -> String
Get string description of Character
"A".ord -> Int
Get int representation of character
Date Extensions
Date.from(#year: Int, month: Int, day: Int) -> NSDate
Returns a new Date given the year month and day
Date.from(#unix: Double) -> NSDate
Returns a new Date given the unix timestamp (timeIntervalSince1970)
Date.parse(dateStr: String, format: String = "yyyy-MM-dd") -> NSDate
Parses the date based on the format and return a new Date
Date.unix(date: NSDate = NSDate()) -> Double
Returns the unix timestamp of the date passed in or the current unix timestamp
Int.hour.fromNow
et al.
Use the following syntax to calculate dates and times based on the user's current calendar.
Dictionary Extensions
merge<K, V>(dictionaries: Dictionary<K, V>...)
Merges the dictionary with dictionaries passed. The latter dictionaries will override values of the keys that are already set
Int Extensions
times(callback: (Int) -> ())
Invoke a callback n times with callback that takes index
times (function: () -> ())
Invoke a callback n times
char -> Character
Get ASCII character from integer
isEven
Check if int is even
isOdd
Check if int is odd
digits() -> [Int]
Splits the int into array of digits
lcm() -> Int
LCM method return least common multiple with number passed
gcd() -> Int
GCD method return greatest common denominator with number passed
random() -> Int
Returns random number from 0 upto but not including value of integer
factorial() -> Int
Returns factorial of integer
isIn(interval) -> Bool
Returns true if i is in interval or range
next() -> Int
Get the next int
prev() -> Int
Get the previous int
upTo(limit: Int, callback: () -> ())
Invoke the callback from int up to and including limit
downTo(limit: Int, callback: () -> ())
Invoke the callback from int down to and including limit
String Extensions
.length
Get the length of the string
.camelCase
Get the camel case representation of the string
.kebabCase
Get the kebab case representation of the string
.snakeCase
Get the snake case representation of the string
.startCase
Get the start case representation of the string
=~ str: String -> Bool
Does a regex match of whether regex string on the right is matches the string on the left
* n: Int -> String
Get string concatenated n
times
[i: Int] -> Character?
Get character at a subscript
[str: String] -> String?
Returns the substring based on the first regex match passed in the subscript
[r: Range<Int>] -> String
Get substring using subscript notation and by passing a range
indexOf(char: Character) -> Int?
Get the start index of character
indexOf(str: String) -> Int?
Get the start index of string
indexOf(pattern: String) -> Int?
Get the start index of regex pattern inside the string
split(delimiter: Character) -> [String]
Get an array from string split using the delimiter character
lstrip() -> String
Get string without leading spaces
rstrip() -> String
Get string without trailing spaces
strip() -> String
Get string without leading or trailing spaces
Regex
init
Init with regex pattern as string
matches(testStr: String) -> [AnyObject]
Return matches based on String passed.
test(testStr: String) -> Bool
escapeStr(str: String) -> String
Escape string with regex characters
Range Extensions
equals - ==
Check the equality of two ranges
eachWithIndex(callback: (T) -> ())
For each index in the range invoke the callback by passing the item in range
each(callback: () -> ())
For each index in the range invoke the callback
Contributing
If you are interested in contributing checkout CONTRIBUTING.md