Get lighter or darker variants of colors instances:
let color = UIColor(red: 0.5, green: 0.5, blue: 1.0, alpha: 1.0)
let lighter = color.lighter(amount: 0.5)
let darker = color.darker(amount: 0.5)
// OR
let lighter = color.lighter()
let darker = color.darker()
let color = NSColor(red: 0.5, green: 0.5, blue: 1.0, alpha: 1.0)
let lighter = color.lighter(amount: 0.5)
let lighter = color.lighter()
// OR
let darker = color.darker(amount: 0.5)
let darker = color.darker()
Data Extension
Initialize from hex string:
let hexString = "6261736520313020697320736F2062617369632E206261736520313620697320776865726520697427732061742C20796F2E"
let data = Data(hexString: hexString)
Get hex string from data:
let data = Data(...)
let string = data.toHexString()
// string = "6261736520313020697320736F2062617369632E206261736520313620697320776865726520697427732061742C20796F2E" if using previous example value
Get UInt8 Array from data:
let data = Data(...)
let array = data.bytesArray
Map Data to Dictionary:
let dictionary = try data.toDictionary()
Date extension
Initialize from string:
let format = "yyyy/MM/dd"
let string = "2015/03/11"
print(Date(fromString: string, format: format)) // Optional("2015/03/11 00:00:00 +0000")
Convert date to string:
let now = Date()
print(now.string())
print(now.string(dateStyle: .medium, timeStyle: .medium))
print(now.string(format: "yyyy/MM/dd HH:mm:ss"))
See how much time passed:
let now = Date()
let later = Date(timeIntervalSinceNow: -100000)
print(later.days(since: now)) // 1.15740740782409
print(later.hours(since: now)) // 27.7777777733571
print(later.minutes(since: now)) // 1666.66666641732
print(later.seconds(since: now)) // 99999.999984026
Check if a date is in future or past:
let later = Date(timeIntervalSinceNow: -100000)
print(now.isInFuture) // false
print(now.isInPast) // true
var string = "4242"
print(string.isNumber) // true
var string = "test"
print(string.isNumber) // false
Check if it’s a valid email:
var string = "test@gmail.com"
print(string.isEmail) // true
var string = "test@"
print(string.isEmail) // false
Check if it’s a valid IP address:
let ip4 = "1.2.3.4"
let ip6 = "fc00::"
let notIPAtAll = "i'll bribe you to say i'm an ip address!"
ip4.isIP4Address //true
ip4.isIP6Address //false
ip4.isIPAddress //true
ip6.isIP4Address //false
ip6.isIP6Address //true
ip6.isIPAddress //true
notIPAtAll.isIP4Address //false
notIPAtAll.isIP6Address //false
notIPAtAll.isIPAddress //false
Uncamelize a string:
var camelString = "isCamelled"
print(camelString.uncamelize) // is_camelled
Capitalize the first letter:
var string = "hello world"
string = string.capitalizedFirst
print(string)// Hello world
Trimmed spaces and new lines:
var string = " I' am a test \n "
print(string.trimmed()) // I'am a test
Truncated to have a limit of characters:
var string = "0123456789aaaa"
print(string.truncate(limit: 10)) // 0123456789...
Split string in chunks of n elements:
let string = "abcd"
print(string.split(intoChunksOf: 2)) // ["ab", "cd"]
Timer extension
Schedule timer every seconds:
var count = 0
Timer.every(1.second, fireImmediately: true) { timer in // fireImmediately is an optional parameter, defaults to false
print("Will print every second")
if count == 3 {
timer.invalidate()
}
count++
}
Schedule timer after a certain delay:
Timer.after(2.seconds) { _ in
print("Prints this 2 seconds later in main queue")
}
Manual scheduling a timer:
let timer = Timer.new(every: 2.seconds) { _ in
print("Prints this 2 seconds later in main queue")
}
timer.start(onRunLoop: RunLoop.current, modes: RunLoopMode.defaultRunLoopMode)
Manual scheduling a timer with a delay:
let timer = Timer.new(after: 2.seconds) { _ in
print("Prints this 2 seconds later in main queue")
}
timer.start(onRunLoop: RunLoop.current, modes: RunLoopMode.defaultRunLoopMode)
URL extension
Get query parameters from URL:
let url = URL(string: "http://example.com/api?v=1.1&q=google")
let queryParameters = url?.queryParameters
print(queryParameters?["v"]) // 1.1
print(queryParameters?["q"]) // google
print(queryParameters?["other"]) // nil
Add skip backup attributes to you URL:
let url = URL(string: "/path/to/your/file")
url?.addSkipBackupAttribute() // File at url won't be backupped!
UserDefaults extension
Get and set values from UserDefaults with subscripts:
let Defaults = UserDefaults.standard
Defaults["userName"] = "test"
print(Defaults["userName"]) // test
Check if the UserDefaults has a key:
UserDefaults.has(key: "aKey")
// OR
UserDefaults.standard.has(key: "aKey")
Each localization of our project applied to a preview
Different dynamic type sizes applied
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
UIElementPreview(ContentView(),
previewLayout: .sizeThatFits, // default is `.device`
previewDevices: ["iPhone SE"], // default is iPhone SE and iPhone XS Max. Note: it won't be used if `previewLayout` is `.sizeThatFits`
dynamicTypeSizes:[.extraSmall] // default is: .extraSmall, .large, .extraExtraExtraLarge
)
}
}
SwiftUI Extensions
Binding extension
Pass an interactive value that’ll act as a preview stand-in for a binding:
struct MyButton: View {
@Binding var isSelected: Bool
// ...
}
struct MyButton_Previews: PreviewProvider {
static var previews: some View {
MyButton(isSelected: .mock(true))
}
}
UIKit Extensions
UIAlertController extension
Create a custom UIAlertController:
let alertController1 = UIAlertController(title: "Title",
message: "Message")
let alertController2 = UIAlertController(title: "Title",
message: "Message",
defaultActionButtonTitle: "Cancel")
let alertController3 = UIAlertController(title: "Title",
message: "Message",
defaultActionButtonTitle: "Cancel",
defaultActionButtonStyle: .cancel)
let alertController1 = UIAlertController(title: "Title",
message: "Message",
defaultActionButtonTitle: "Cancel",
defaultActionButtonStyle: .cancel,
tintColor: .blue)
UIApplication.shared.topViewController() // Using UIWindow's rootViewController as baseVC
UIApplication.shared.topViewController(from: baseVC) // topVC from the base view controller
Get the app delegate:
UIApplication.delegate(AppDelegate.self)
Open app settings:
UIApplication.shared.openAppSettings()
Open app review page:
let url = URL(string: "https://itunes.apple.com/app/{APP_ID}?action=write-review")
UIApplication.shared.openAppStoreReviewPage(url)
UIButton extension
Add right image with custom offset to button:
let button = UIButton(frame: .zero)
button.addRightImage(image, offset: 16)
UICollectionView extension
Register and dequeue safely your UICollectionViewCell:
// 1. Make your `UICollectionCell` conforms to `Reusable` (class-based) or `NibReusable` (nib-based)
final class ReusableClassCollectionViewCell: UICollectionViewCell, Reusable {}
// 2. Register your cell:
collectionView.register(cellType: ReusableClassCollectionViewCell.self)
// 3. Dequeue your cell:
let cell: ReusableClassCollectionViewCell = collectionView.dequeueReusableCell(at: indexPath)
Register and dequeue safely your UICollectionReusableView:
// 1. Make your `UICollectionReusableView` conforms to `Reusable` (class-based) or `NibReusable` (nib-based)
final class ReusableNibCollectionReusableView: UICollectionReusableView, NibReusable
// 2. Register your cell:
collectionView.register(supplementaryViewType: ReusableNibCollectionReusableView.self, ofKind: UICollectionView.elementKindSectionHeader)
// 3. Dequeue your cell:
let header: ReusableNibCollectionReusableView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, at: indexPath)
UICollectionViewCell extension
Apply a corner radius to the cell:
let cell = UICollectionViewCell()
cell.applyCornerRadius(10)
Animate when cell is highlighted:
class MyCollectionViewCell: UICollectionViewCell {
// ...
override var isHighlighted: Bool {
willSet {
self.animate(scale: newValue, options: .curveEaseInOut) // Note that the animation is customisable, but all parameters as default value
}
}
// ...
}
UIFont extension
Obtains a font that scale to support Dynamic Type:
let font = UIFont.dynamicStyle(.body, traits: .traitsBold)
UIDevice extension
Access to your device information:
print(UIDevice.idForVendor) // 104C9F7F-7403-4B3E-B6A2-C222C82074FF
print(UIDevice.systemName()) // iPhone OS
print(UIDevice.systemVersion()) // 9.0
print(UIDevice.deviceName) // iPhone Simulator / iPhone 6 Wifi
print(UIDevice.deviceLanguage) // en
print(UIDevice.isPhone) // true or false
print(UIDevice.isPad) // true or false
// 1. Make your `UITableViewCell` conforms to `Reusable` (class-based) or `NibReusable` (nib-based)
final class ReusableClassTableViewCell: UITableViewCell, Reusable {}
// 2. Register your cell:
tableView.register(cellType: ReusableClassTableViewCell.self)
// 3. Dequeue your cell:
let cell: ReusableClassTableViewCell = tableView.dequeueReusableCell(at: indexPath)
Register and dequeue safely your UITableViewHeaderFooterView:
// 1. Make your `UITableViewHeaderFooterView` conforms to `Reusable` (class-based) or `NibReusable` (nib-based)
final class ReusableClassHeaderFooterView: UITableViewHeaderFooterView, Reusable {}
// 2. Register your header or footer:
tableView.register(headerFooterViewType: ReusableClassHeaderFooterView.self)
// 3. Dequeue your header or footer:
let cell: ReusableClassHeaderFooterView = tableView.dequeueReusableHeaderFooterView()
Find the first subview corresponding to a specific type:
let scrollView: UIScrollView? = aView.findView()
Add a SwiftUI View as a subview:
aView.addSubSwiftUIView(SwiftUIView())
Automates your localizables:
aView.translateSubviews()
It will iterate on all the subviews of the view, and use the text / placeholder as key in NSLocalizedString.
By settings your localizable key in your xib / storyboard, all yours string will be automatically translated just by calling the above method.
Add constraints between a view and its superview:
aView.addConstraints() // Add constraints to all edges with zero insets
aView.addConstraints(to: [.top, .bottom]) // Add constraints to top and bottom edges with zero insets
aView.addConstraints(to: [.top, .left], insets: UIEdgeInsets(top: 10, left: 20, bottom: 0, right: 0)) // Add constraints to top and left edges with custom insets
UIViewController extension
Generate a Xcode preview for any view controllers:
@available(iOS 13, *)
struct MyViewPreview: PreviewProvider {
static var previews: some View {
MyViewController().preview
}
}
Reset the navigation stack by deleting previous view controllers:
Add a SwiftUI View as a child of the input UIView:
vc.addSubSwiftUIView(SwiftUIView(), to: vc.view)
UIKit Protocols:
NibLoadable
Make your UIView subclasses conform to this protocol to instantiate them from their NIB safely.
Note: Be sure that your UIView is based on a Nib, and is used as the Xib’s root view.
class NibLoadableView: UIView, NibLoadable {
// ...
}
let view = NibLoadableView.loadFromNib()
NibOwnerLoadable
Make your UIView subclasses conform to this protocol to instantiate them from their Xib’s File Owner safely.
Note: Be sure that your UIView is based on a Nib, and is used as the Xib’s File’s Owner.
class NibLoadableView: UIView, NibOwnerLoadable {
// ...
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.loadNibContent()
}
}
// Then use it directly from another xib or whatever...
AppKit, Cocoa Extensions
NSView extension
Change the frame of the view easily
let aView = NSView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
aView.x += 100 // move to right
aView.y += 100 // move downwards
aView.width -= 10 // make the view narrower
aView.height -= 10 // make the view shorter
Automates your localizables
aView.convertLocalizables()
It will iterate on all the subviews of the view, and use the text / placeholder as key in NSLocalizedString.
By settings your localizable key in your xib / storyboard, all yours string will be automatically translated just by calling the above method.
Protocols
Injectable
Protocol to do ViewController Data Injection with Storyboards and Segues in Swift. Inspired from Nastasha’s blog:
class RedPillViewController: UIViewController, Injectable {
@IBOutlet weak private var mainLabel: UILabel!
// the type matches the IOU's type
typealias T = String
// this is my original dependency (IOU)
// I can now make this private!
private var mainText: String!
override func viewDidLoad() {
super.viewDidLoad()
// this will crash if the IOU is not set
assertDependencies()
// using the IOU if needed here,
// but using it later is fine as well
mainLabel.text = mainText
}
// Injectable Implementation
func inject(text: T) {
mainText = text
}
func assertDependencies() {
assert(mainText != nil)
}
}
// ViewController that will inject data...
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
switch segueIdentifierForSegue(segue) {
case .TheRedPillExperience
let redPillVC = segue.destinationViewController as? RedPillViewController
redPillVC?.inject("😈")
case .TheBluePillExperience:
let bluePillVC = segue.destinationViewController as? BluePillViewController
bluePillVC?.inject("👼")
}
}
Occupiable
The following use cases works for String Array, Dictionary, and Set
SwiftyUtils
SwiftyUtils groups all the reusable code that we need to ship in each project. This framework contains:
Working on iOS, macOS, tvOS, and watchOS, everything has been made to be easy to use! 🎉
Contents
Check out the repository to find examples / tests for each feature.
Swift, Foundation and CoreGraphics extensions:
SwiftUI:
SwiftUI Extension:
UIKit Extensions:
UIKit Protocols:
AppKit Extensions:
Protocols:
PropertyWrappers:
Others:
Swift, Foundation and CoreGraphics Extensions
Array extension
Safely access to an element:
Find all the index of an object:
Get index of first / last occurrence of an object:
Remove an object:
Remove all the duplicates:
Remove all instances of an item:
Check if an array is a subset of another array:
Determine if an array contains an object:
Get intersection and union of two arrays:
Get difference between two arrays:
Split into chunk of a specific size:
Bundle extension
Get bundle information:
CGFloat extension
Create a CGFloat from a Float or an Integer:
CGPoint extension
Add two
CGPoint
:Substract two
CGPoint
:Multiply a
CGPoint
with a scalar:CGRect extension
Get the origin’s x and y coordinates:
Change one property of a
CGRect
:CGSize extension
Add two
CGSize
:Substract two
CGSize
:Multiply a
CGSize
with a scalar:Color extension
Create colors with HEX values:
Access to individual color value:
Get lighter or darker variants of colors instances:
Data Extension
Initialize from hex string:
Get hex string from data:
Get UInt8 Array from data:
Map Data to Dictionary:
Date extension
Initialize from string:
Convert date to string:
See how much time passed:
Check if a date is in future or past:
Dictionary extension
Check if a key exists in the dictionary:
Map Dictionary to Data:
Easily get union of two dictionaries:
map
a dictionary:flatMap
a dictionary:Get difference of two dictionaries:
Merge several dictionaries:
Double extension
Get the time interval for a number of milliseconds, seconds, hour, or days:
Formatted value with the locale currency:
FileManager extension
Get documents directory url following the os:
Create a new directory:
Delete contents of temporary directory
Delete contents of documents directory
Int extension
Round to the nearest / nearest down / nearest up:
Formatted value with the locale currency:
MutableCollection extension
Sorts the mutable collection in place using
KeyPath
:NotificationCenter extension
Post a notification from a specific queue:
NSAttributedString extension
Check if an attribute is applied on the desired substring:
NSLayoutConstraint extension
No available for watchOS
Apply a multiplier to a constraint (currently working only for width and height):
NSMutableAttributedString extension
Colorize each occurence:
Colorize everything after an occurence:
Strike each occurence:
Strike everything after an occurence:
Underline each occurence:
Underline everything after an occurence:
Use custom font for each occurence:
Custom font for everything after an occurence:
NSObject extension
Get the class name of a
NSObject
:NSRange extension
Range after an occurence:
Range of string:
ReusableFormatters
Reuse your formatter to avoid heavy allocation:
Sequence extension
Sort a sequence using
keyPath
:String extension
Access with subscript:
Check if it contains a string:
Check if it’s a number:
Check if it’s a valid email:
Check if it’s a valid IP address:
Uncamelize a string:
Capitalize the first letter:
Trimmed spaces and new lines:
Truncated to have a limit of characters:
Split string in chunks of n elements:
Timer extension
Schedule timer every seconds:
Schedule timer after a certain delay:
Manual scheduling a timer:
Manual scheduling a timer with a delay:
URL extension
Get query parameters from URL:
Add skip backup attributes to you URL:
UserDefaults extension
Get and set values from
UserDefaults
with subscripts:Check if the
UserDefaults
has a key:Remove all values in
UserDefaults
:SwiftUI
UIElementPreview
Generate automatically multiple previews including:
SwiftUI Extensions
Binding extension
Pass an interactive value that’ll act as a preview stand-in for a binding:
UIKit Extensions
UIAlertController extension
Create a custom
UIAlertController
:Show an
UIAlertController
:Add an action to the
UIAlertController
:UIApplication extension
Get the current view controller display:
Get the app delegate:
Open app settings:
Open app review page:
UIButton extension
Add right image with custom offset to button:
UICollectionView extension
Register and dequeue safely your
UICollectionViewCell
:Register and dequeue safely your
UICollectionReusableView
:UICollectionViewCell extension
Apply a corner radius to the cell:
Animate when cell is highlighted:
UIFont extension
Obtains a font that scale to support Dynamic Type:
UIDevice extension
Access to your device information:
Check your system version:
Force device orientation:
UIImage extension
Create an image from a color:
Fill an image with a color:
Combined an image with another:
Change the rendering mode:
UILabel extension
Configure a dynamic text style to the label:
Detect if a label text is truncated:
Customize label line height:
Customize the label truncated text (replace the default
...
):UIScreen extension
Get the screen orientation:
Get the screen size:
Get the status bar height:
UISlider extension
Get the value where the user tapped using an
UITapGestureRecognizer
:UIStoryboard extension
Get the application’s main storyboard:
UISwitch extension
Toggle
UISwitch
:UITableView
Register and dequeue safely your
UITableViewCell
:Register and dequeue safely your
UITableViewHeaderFooterView
:UITextField extension
Configure a dynamic text style to the textfield:
Modify clear button image:
Modify placeholder’s color:
UITextView extension
Configure a dynamic text style to the textfield:
UIView extension
Change the frame of the view easily:
Apply a corner radius to the view:
Find the
ViewController
which contains this view:Find a subview using its `accessibilityIdentifier, useful to tests private outlets:
Find the first subview corresponding to a specific type:
Add a SwiftUI
View
as a subview:Automates your localizables:
It will iterate on all the subviews of the view, and use the text / placeholder as key in
NSLocalizedString
. By settings your localizable key in your xib / storyboard, all yours string will be automatically translated just by calling the above method.Add constraints between a view and its superview:
UIViewController extension
Generate a Xcode preview for any view controllers:
Reset the navigation stack by deleting previous view controllers:
Check if ViewController is onscreen and not hidden:
Check if ViewController is presented modally:
Open Safari modally:
Add a child view controller to another controller:
Add a child view controller to a container view:
Remove a child view controller:
Add a SwiftUI
View
as a child of the inputUIView
:UIKit Protocols:
NibLoadable
Make your
UIView
subclasses conform to this protocol to instantiate them from their NIB safely. Note: Be sure that yourUIView
is based on a Nib, and is used as the Xib’s root view.NibOwnerLoadable
Make your
UIView
subclasses conform to this protocol to instantiate them from their Xib’s File Owner safely. Note: Be sure that yourUIView
is based on a Nib, and is used as the Xib’s File’s Owner.AppKit, Cocoa Extensions
NSView extension
Change the frame of the view easily
Automates your localizables
It will iterate on all the subviews of the view, and use the text / placeholder as key in
NSLocalizedString
. By settings your localizable key in your xib / storyboard, all yours string will be automatically translated just by calling the above method.Protocols
Injectable
Protocol to do
ViewController
Data Injection with Storyboards and Segues in Swift. Inspired from Nastasha’s blog:Occupiable
The following use cases works for String Array, Dictionary, and Set
isEmpty
/isNotEmpty
No optional types only
isNilOrEmpty
Optional types only
Then
Syntactic sugar for Swift initializers:
PropertyWrappers
UserDefaultsBacked
Type safe access to UserDefaults with support for default values.
Others
UnitTesting
Grand Central Dispatch sugar syntax:
Detect if UITests are running:
Measure tests performance:
UITesting
Detect if UITests are running:
Shell Utility
(macOS only)
Runs a command on a system shell and provides the return code for success, STDOUT, and STDERR.
STDOUT as one continuous String:
STDOUT as array of Strings separated by newlines:
Installation
Manually
Copy the SwiftyUtils folder into your Xcode project. (Make sure you add the files to your target(s))
CocoaPods
Add
pod SwiftyUtils
to your Podfile.Carthage
Add
github "tbaranes/SwiftyUtils"
to your Cartfile.Swift Package Manager
You can use The Swift Package Manager to install
SwiftyUtils
by adding the proper description to yourPackage.swift
file:Feedback
Contact
License
SwiftyUtils is under the MIT license. See the LICENSE file for more information. dic.testAll