Utility methods, polyfills, and operators to simplify common tasks in Swift.
...
runOnMainThread
runOnMainThreadIfNeeded
runOnMainThreadIfNeededSync
runOnMainThreadAfterDelay
runAsync
runAsyncAfterDelay
abs
acos
asin
atan
atan2
cos
sin
tan
exp
exp2
lerp
log
log10
log2
pow
sqrt
floor
ceil
round
clamp
Adds +
, -
, *
, /
operators for two points and point with scalar.
Adds +
, -
, *
, /
operators for two sizes and size with scalar.
NSDate.currentTZOffset
NSDate.currentTZOffsetMinutes
init(dateString)
toISOString
toRFC3339String
unixTimestamp
shortRelativeString
midnight
addSeconds
addMinutes
addHours
addDays
addWeeks
addMonths
addYears
isAfter
isBefore
year
month
weekOfMonth
weekday
days
hours
minutes
seconds
Adds +
, -
, +=
, -=
, ==
, <
operators for NSDate.
startsWith
endsWith
contains
match
replace
split
substr
trim
uriEncoded
md5Sum
rangeWithOffsets
toStringRange
fullNSRange
length
utf8Length
utf16Length
isValidURL
isValidEmail
Adds ==
operator for Range<ForwardIndexType>
.
typealias to NSColor
on non-iOS, missing init(red, green, blue, alpha)
added.
typealias to NSImage
on non-iOS, missing init(CGImage)
and CGImage
added.
### Array.compact(array: [T?]) -> [T]
Convert an array of optional types to non-optional types by removing any nil entries.
Arguments
array
- Array of optional typesreturns
A copy of the given array, typecasted with nil entries removed
Example
let compacted: [Int] = [1, 2, nil, 3].compact()
### Array#indexOf(item: U) -> Int?
Return the index of the first array element equal to item
.
Arguments
item
- The item to search forreturns
A zero-based index for the first matching element in the array, otherwise nil
Example
if let index = [1, 2, 3].indexOf(2) { ... }
### Array#indexOf(condition: TestCallback) -> Int?
Return the index of the first array element where the supplied function returns true.
Arguments
condition
- Function that takes an array element and returns true for a match, otherwise falsereturns
A zero-based index for the first matching element in the array, otherwise nil
Example
if let index = [1, 2, 3].indexOf({ $0 == 2 }) { ... }
### Array#each(function: ElementCallback)
Execute a function for each element in the array.
Arguments
function
- Function to run for each element
Example
[1, 2, 3].each { println($0) }
### Array#each(function: IndexedElementCallback)
Execute a function for each index and element tuple in the array.
Arguments
function
- Function to run for each index and element tuple
Example
[1, 2, 3].each { println("Index \($0) = \($1)") }
### Array#contains(items: T...) -> Bool
Test if the array contains one or more elements.
Arguments
items
- One or more elements to search for in the array. The array must contain all of the given elements for this method to return truereturns
True if all of the given elements were found in the array, otherwise false
Example
if [1, 2, 3].contains(2, 3) { ... }
### Array#some(test: TestCallback) -> Bool
Test if any of the array elements pass a given condition.
Arguments
test
- Function that takes an array element and returns true or falsereturns
True the first time an array element passes the test function, otherwise false
Example
if [1, 2, 3].some({ $0 == 2 }) { ... }
### Array#every(test: TestCallback) -> Bool
Test if all of the array elements pass a given condition.
Arguments
test
- Function that takes an array element and returns true or falsereturns
True if every array element passes the test function, otherwise false the first time an element fails the test
Example
if [1, 2, 3].every({ $0 is Int }) { ... }
### Array#joinWithString(separator: String) -> String
Flatten the elements of this array into a string, with the separator
string between each element in the output string.
Arguments
separator
- String to place between each elementreturns
A string representation of the array
Example
[1, 2, 3].joinWithString("-") // "1-2-3"
### Array#chooseRandom() -> T?
Return a randomly chosen element from the array.
Arguments
returns
A randomly chosen element, or nil if the array is empty
Example
if let num = [1, 2, 3].chooseRandom() { println("Chose \(num)") }
### Array#pop() -> Element?
Remove the last element from the array and return it.
Arguments
returns
The last element in the array, or nil if the array is empty
Example
[1, 2, 3].pop() // Array becomes [1, 2]
### Array#shift() -> Element?
Remove the first element from the array and return it.
Arguments
returns
The first element in the array, or nil if the array is empty
Example
[1, 2, 3].shift() // Array becomes [2, 3]
### Array#unshift(item: T)
Add an element to the beginning of the array.
Arguments
item
- New item to prepend to the array
Example
[1, 2, 3].unshift(0) // Array becomes [0, 1, 2, 3]
### Array#fill(value: Element, count: Int)
Add an element to the array a given number of times.
Arguments
value
- New element to append to the arraycount
- Number of times to append the new element
Example
[].fill("a", 3) // Array becomes ["a", "a", "a"]
### CGRect#aspectFill(toRect: CGRect) -> CGRect
Scales this rectangle to fill another rectangle. Some portion of this rectangle may extend beyond the bounds of the target rectangle to fill the target rectangle
Arguments
toRect
- Target rectangle to fillreturns
A copy of this rectangle, scaled to fill the target rectangle
Example
CGRectMake(0, 0, 4, 5).aspectFill(CGRectMake(0, 0, 100, 100)) // Returns { 0, -12.5, 100, 125 }
### CGRect#aspectFit(toRect: CGRect) -> CGRect
Scales this rectangle to fill the interior of another rectangle while maintaining this rectangle's aspect ratio
Arguments
toRect
- Target rectangle to fit inside ofreturns
A copy of this rectangle, scaled to fit the target rectangle
Example
CGRectMake(0, 0, 4, 5).aspectFit(CGRectMake(0, 0, 100, 100)) // Returns { 10, 0, 80, 100 }
### CGSize#aspectFill(toSize: CGSize) -> CGSize
Scales this size to fill a rectangle. Some portion of this size may extend beyond the bounds of the rectangle to fill the rectangle
Arguments
toRect
- Target rectangle to fillreturns
A copy of this size, scaled to fill the target rectangle
Example
CGSizeMake(4, 5).aspectFill(CGSizeMake(100, 100)) // Returns { 100, 125 }
### CGSize#aspectFit(toSize: CGSize) -> CGSize
Scales this size to fill the interior of a rectangle while maintaining this size's aspect ratio
Arguments
toRect
- Target rectangle to fit inside ofreturns
A copy of this size, scaled to fit the target rectangle
Example
CGSizeMake(4, 5).aspectFill(CGSizeMake(100, 100)) // Returns { 80, 100 }
### Dictionary.sortByKeys(dictionary: [K: V]) -> [V]
Convert a dictionary to an array of values sorted by the dictionary keys
Arguments
dictionary
- Dictionary to sortreturns
An array of values sorted by their corresponding keys in the dictionary
Example
Dictionary.sortByKeys([2: "a", 1: "b"]) // Returns ["b", "a"]
### Dictionary#map (transform: (Key, Value) -> (K, V)) -> [K: V]
Map all of the (key, value)
tuples in this dictionary to new key value
pairs in a new dictionary. The behavior is undefined for two or more
keys mapping to the same output key
Arguments
transform
- Function that is called once for each key value pair and returns a new key value pairreturns
Dictionary consisting of the mapped key value pairs
Example
["a": 1, "b": 2].map { return ("*" + $0, $1 * 3) } // Returns ["*a": 3, "*b": 6]
### Double#abs() -> Double
Return the absolute value of this number
Arguments
returns
fabs(self)
### Double#sqrt() -> Double
Return the square root of this number
Arguments
returns
sqrt(self)
### Double#floor() -> Double
Return this number rounded down to the nearest whole number
Arguments
returns
floor(self)
### Double#ceil() -> Double
Return this number rounded up to the nearest whole number
Arguments
returns
ceil(self)
### Double#round() -> Double
Return this number rounded to the nearest whole number
Arguments
returns
round(self)
### Double#clamp(min: Double, _ max: Double) -> Double
Return this value clamped to the closed interval defined by min
and
max
Arguments
min
- Inclusive minimum valuemax
- Inclusive maximum valuereturns
Swift.max(min, Swift.min(max, self))
### Double.random(min: Double = 0, max: Double = 1) -> Double
Return a uniformly distributed random number in the half open interval
[min, max)
Arguments
min
- Inclusive minimum valuemax
- Exclusive maximum valuereturns
A random number within the given interval
### NSData#base64URLEncode() -> String
Convert this NSData to a URL-safe base64 encoded string. URL-safe
encoding replaces +
and /
with -
and _
, respectively, and does
not contain =
padding characters. For more information see
https://en.wikipedia.org/wiki/Base64#URL_applications
Arguments
returns
A URL-safe base64 encoded string
### NSData#toHexString() -> String
Convert this NSData to a hexadecimal string. The output will not include a "0x" prefix
Arguments
returns
A hexadecimal string
### NSDate#currentTZOffset() -> NSTimeInterval
Returns the current system local timezone as the number of seconds offset from GMT.
Arguments
returns
Example: -25200 seconds for Pacific Daylight Time
### NSDate#currentTZOffsetMinutes() -> Int
Returns the current system local timezone as the number of minutes offset from GMT. :returns: Example: -420 minutes for Pacific Daylight Time
### NSDate#toISOString() -> String
Returns this date as an ISO 8601 string.
Arguments
returns
ISO 8601 formatted string. Example: "2008-09-22T14:01:54.957Z"
### NSDate#toRFC3339String() -> String
Returns this date as an RFC 3339 string.
Arguments
returns
RFC 3339 formatted string. Example: "2002-10-02T10:00:00-05:00"
### NSDate#unixTimestamp() -> Int64
Returns this date as a UNIX timestamp (number of whole seconds passed since the UNIX epoch).
Arguments
returns
64-bit integer timestamp. Example: 1435383187
### NSDate#shortRelativeString(otherDate: NSDate) -> String
Returns the difference between this date and another date as a short human-friendly string. Examples: "now", "3m", "5h", "1w", "2015y".
Arguments
otherDate
- Other date to compare this date against. The absolute difference between the two dates is used.returns
A short string representation of the time difference between the two dates
### NSDate#midnight() -> NSDate
Returns an NSDate for midnight of the same day as this date.
Arguments
returns
NSDate at midnight
### NSDate#addSeconds(seconds: Int) -> NSDate
Returns a new date by adding seconds to the current date.
### NSDate#addMinutes(minutes: Int) -> NSDate
Returns a new date by adding minutes to the current date.
### NSDate#addHours(hours: Int) -> NSDate
Returns a new date by adding hours to the current date.
### NSDate#addDays(days: Int) -> NSDate
Returns a new date by adding days to the current date.
### NSDate#addWeeks(weeks: Int) -> NSDate
Returns a new date by adding weeks to the current date.
### NSDate#addMonths(months: Int) -> NSDate
Returns a new date by adding months to the current date.
### NSDate#addYears(years: Int) -> NSDate
Returns a new date by adding years to the current date.
### NSDate#isAfter(date: NSDate) -> Bool
Test if a given date occurs after this date.
Arguments
date
- Date to test against this datereturns
True if the given date is ahead of this date, otherwise false if it is equal to or behind this date.
### NSDate#isBefore(date: NSDate) -> Bool
Test if a given date occurs before this date.
Arguments
date
- Date to test against this datereturns
True if the given date is behind this date, otherwise false if it is equal to or ahead of this date.
### NSObject#getAssociatedObject(key: UnsafePointer) -> T?
Retrieve an associated object. Associated objects allow NSObject-derived objects to be associated with a parent NSObject-derived object and a given key. They are particularly useful for adding new members to an object via extensions.
Arguments
key
- Key used to store the associated object being retrievedreturns
Value associated with the given key on this object if it exists and matches the expected type, otherwise nil
Example
extension UIViewController {
private static var key = "myPropertyKey"
var myProperty: String? { return getAssociatedObject(&UIViewController.key) as? String }
}
### NSObject#setAssociatedObject(key: UnsafePointer, _ value: T?)
Set an associated object. Associated objects allow NSObject-derived objects to be associated with a parent NSObject-derived object and a given key. They are particularly useful for adding new members to an object via extensions.
Arguments
key
- Key used to store the associated objectvalue
- Object to store
Example
extension UIViewController {
private static var key = "myPropertyKey"
var myProperty: String? {
get { return getAssociatedObject(&UIViewController.key) as? String }
set { setAssociatedObject(&UIViewController.key, newValue as NSString?) }
}
}
### NSObject#lazyAssociatedObject(key: UnsafePointer, initializer: () -> T) -> T
Retrieve an associated object that is lazily initialized. See
getAssociatedObject
for more information on associated objects.
Arguments
key
- Key used to store the associated object being retrievedinitializer
- Function that instantiates the associated object This method is run only once the first time the object is accessed
Example
extension UIViewController {
private static var key = "myPropertyKey"
var myProperty: MyComplexObject {
return lazyAssociatedObject(&UIViewController.key)
{ MyComplexObject() } as? MyComplexObject
}
}
### NSRegularExpression#exec(string: String) -> RegExpMatches
Execute this regular expression against a given string and return all matches and capture groups.
Arguments
haystack
- The string to execute this regular expression againstreturns
ARegExpMatches
object containing each match which in turn contains the matching value, range, and capture groups
Example
for match in RegExp("(\\w+)")!.exec("hello world") {
println(match.captureGroups.first)
}
### NSRegularExpression#test(string: String) -> Bool
Test if this regular expression matches one or more times against a given string.
Arguments
string
- The string to test this regular expression againstreturns
True ifthe regular expression matched one or more times, otherwise false
### NSString#startsWith(prefix: String) -> Bool
Test if this string starts with a given string.
Arguments
prefix
- String to test against the beginning of the current stringreturns
True if this string starts with the given prefix
### NSString#endsWith(suffix: String) -> Bool
Test if this string ends with a given string.
Arguments
suffix
- String to test against the ending of the current stringreturns
True if this string ends with the given suffix
### NSString#contains(needle: String) -> Bool
Test if this string contains a given string.
Arguments
needle
- String to search forreturns
True if this string contains the given string
### NSString#match(regex: RegExp) -> [String]
Find all matches in this string for a given regular expression. This
method does not support capture groups (use RegExp#exec()
).
Arguments
regex
- Regular expression to execute against this stringreturns
Array of zero or more
### NSString#replace(target: String, withString replacement: String, options: NSStringCompareOptions = .LiteralSearch, range searchRange: Range? = nil) -> String
Returns a new string by replacing all instances of a given substring with another string.
Arguments
target
- Substring to search and replace in this stringwithString
- Replacement stringoptions
- String comparison optionsrange
- Limit search and replace to a specific rangereturns
New string with all instances oftarget
replaced bywithString
### NSString#split(separator: String) -> [String]
Returns an array containing substrings from this string that have been divided by a given separator.
Arguments
separator
- Separator string to split on. Example: ":"returns
Array of substrings
### NSString#split(separators: NSCharacterSet) -> [String]
Returns an array containing substrings from this string that have been divided by a given set of separator characters.
Arguments
separators
- Separator characters to split onreturns
Array of substrings
### NSString#substr(range: Range) -> String
Returns a substring specified by a given character range.
Arguments
range
- Character range to extractreturns
Extracted substring
### NSString#substr(range: Range) -> String
Returns a substring specified by a given string range.
Arguments
range
- String range to extractreturns
Extracted substring
### NSString#substr(startIndex: Int) -> String
Returns a substring starting at the specified character offset.
Arguments
startIndex
- Inclusive starting character indexreturns
Extracted substring
### NSString#trim() -> String
Returns a string with leading and trailing whitespace and newlines removed.
Arguments
returns
Trimmed string
### NSString#uriEncoded() -> String
Returns a string with non-URI-safe characters escaped using percent encoding.
Arguments
returns
Escaped string
### NSString#md5Sum() -> String
Returns this string's MD5 checksum as a hexidecimal string.
Arguments
returns
32 character hexadecimal string
### NSString#rangeWithOffsets(startOffset: Int = 0, endOffset: Int = 0) -> Range
Construct a string range by specifying relative offsets from the beginning and end of this string.
Arguments
startOffset
- Relative offset from the beginning of this string. Must be >= 0endOffset
- Relative offset from the end of this string. Must be <= 0returns
Range<String.Index>
for this string
### NSString#toStringRange(range: Range) -> Range
Convert a range specified as character positions to a string range.
Arguments
range
- Character position range. Example:(0...5)
returns
Range<String.Index>
for this string
### NSString#toStringRange(range: NSRange) -> Range?
Convert an NSRange to a string range.
Arguments
NSRange
- to convertreturns
Range<String.Index>
for this string
### NSString#fullNSRange() -> NSRange
Returns an NSRange representing the entire length of this string.
Arguments
returns
NSRange
### NSTimer#schedule(delay afterDelay: NSTimeInterval, handler: TimerCallback) -> NSTimer
Schedule a function to run once after the specified delay.
Arguments
delay
- Number of seconds to wait before running the functionhandler
- Function to runreturns
The newly created timer associated with this execution
### NSTimer#schedule(repeatInterval interval: NSTimeInterval, handler: TimerCallback) -> NSTimer
Schedule a function to run continuously with the specified interval.
Arguments
repeatInterval
- Number of seconds to wait before running the function the first time, and in between each successive runhandler
- Function to returnreturns
The newly created timer associated with this execution
### Range#each(function: T -> ())
Execute a function for each element in the range.
Arguments
function
- Function to run for each element
### Range#map(function: T -> V) -> [V]
Map each element in this range to an output value.
Arguments
function
- Function mapping a range element to an output valuereturns
An array of output values
### Range#toArray() -> [T]
Convert this range to an array.
Arguments
returns
An array containing each element in the range
### UIImage#imageWithFill(color: UIColor) -> UIImage
Create a 1x1 image filled with the specified color.
Arguments
color
- Color to fill the image withreturns
New UIImage containing one pixel of the specified color
### Math#lerp(a: Float, b: Float, t: Float) -> Float
Linearly interpolate between two values.
Arguments
a
- Starting valueb
- Ending valuet
- Percent to interpolate froma
tob
, usually in the range [0-1]returns
The interpolated value
Example
lerp(50.0, 100.0, 0.5) // 75.0
### Math#lerp(a: Double, b: Double, t: Double) -> Double
Linearly interpolate between two values.
Arguments
a
- Starting valueb
- Ending valuet
- Percent to interpolate froma
tob
, usually in the range [0-1]returns
The interpolated value
Example
lerp(50.0, 100.0, 0.5) // 75.0
### Threading#lazyThreadLocalObject(key: String, initializer: () -> T) -> T
Retrieve a thread-local object that is lazily initialized. A new thread-local object is instantiated and cached for each thread this method is called on.
Arguments
key
- Key used to store the thread-local being retrievedinitializer
- Function that instantiates the thread-local object This method is run only once per thread, the first time the object is accessed on each thread
Example
lazyThreadLocalObject("my.namespace.object") { return MyObject() }
### Threading#runOnMainThread(block: dispatch_block_t)
Asynchronously schedule a function for execution on the main thread
Arguments
block
- Function to run on the main thread in the (near) future
Example
runOnMainThread { self.collectionView.reloadData() }
### Threading#runOnMainThreadIfNeeded(block: dispatch_block_t)
Asynchronously schedule a function for execution on the main thread if we're currently on a background thread, otherwise synchronously run the function immediately.
Arguments
block
- Function to either asynchronously schedule or run immediately
Example
runOnMainThreadIfNeeded { self.collectionView.reloadData() }
### Threading#runOnMainThreadIfNeededSync(block: dispatch_block_t)
Schedule a function for execution on the main thread and block execution on the current background thread until it completes, or synchronously run the function immediately if we're already on the main thread.
Arguments
block
- Function to either synchronously schedule or run immediately
Example
runOnMainThreadIfNeededSync { myMainThreadWork() }
### Threading#runOnMainThreadAfterDelay(delay: NSTimeInterval, block: dispatch_block_t)
Asynchronously schedule a function for execution on the main thread after at least the given delay.
Arguments
delay
- Minimum number of seconds to wait before executionblock
- Function to run on the main thread in the future
Example
runOnMainThreadAfterDelay(3.0) { self.label.text = "Waited three seconds" }
### Threading#runAsync(block: dispatch_block_t)
Asynchronously schedule a function for execution on a background thread, using the default priority global queue.
Arguments
block
- Function to run on a background thread in the (near) future
Example
runAsync { println("On thread \(NSThread.currentThread().name)") }
### Threading#runAsyncAfterDelay(delay: NSTimeInterval, block: dispatch_block_t)
Asynchronously schedule a function for execution on a background thread after at least the given delay, using the default priority global queue.
Arguments
delay
- Minimum number of seconds to wait before executionblock
- Function to run on a background thread in the future
Example
runAsyncAfterDelay(3.0) {
println("On thread \(NSThread.currentThread().name) after 3 seconds")
}