RDExtensionsSwift
RDExtensionsSwift is a collection of useful extensions for Swift.
It makes your iOS app development much easier and lets you to write simplier and cleaner code.
Content
- Operator Overloads
- Int and Int64 Extensions
- Double Float and CGFloat Extensions
- Bool Extensions
- Character Extensions
- String Extensions
- CGRect Extensions
- CMTime Extensions
- AVPlayerItem Extensions
- Array and Collection Extensions
- NSObject Extensions
- NSData Extensions
- NSDate Extensions
- NSDictionary Extensions
- NSURL Extensions
- PHAsset Extensions
- UIColor Extensions
- UIImage Extensions
- UINib Extensions
- UIView Extensions
- UIScrollView Extensions
- UIAlertView Extensions
- UIAlertController Extensions
- UIImageView Extensions
- UILabel Extensions
- UITextField Extensions
- UITextView Extensions
- UIViewController Extensions
- MPMoviePlayerController Extensions
Operator Overloads
You can add, substract, multiply, divide other type variables without casting them:
let intNumber : Int = 10
let doubleNumber : Double = 5.5
let sum = intNumber + doubleNumber // sum value will be 15.5 DoubleYou are able to concatenate two array into first:
var array1 = [1, 2, 3]
let array2 = [4, 5, 6]
array1 += array2 // array1 value will be [1, 2, 3, 4, 5, 6]Int and Int64 Extensions
Convert int to ascii character:
97.toCharacter // value will be Character("A")Convert int to String:
123.toString // value will be String("123")Double Float and CGFloat Extensions
Convert Double to String:
let d = 123.456789
d.toString = "123.456789"
d.toString() = "123.45"
d.toString(4) = "123.4567" // where 4 is the number of characters after pointBool Extensions
Convert bool to String and Int
true.toString = "true"
false.toString = "false"
true.toInt = 1
false.toInt = 0Character Extensions
Convert Character to Int (by ascii table):
Character("A").toInt = 97String Extensions
Convert String to bool, Int, Double, CGFloat, HTTP URL, File Path etc...
("TRUE" | "True" | "true" | "YES" | "Yes" | "yes" | "1").toBool = true
("FALSE" | "False" | "false" | "NO" | "No" | "no" | "0").toBool = false
"123".toInt = 123
"123".toDouble = Double(123)
"123".toCGFloat = CGFloat(123)
"http://example.com/".toHttpURL = NSURL(sting: "http://example.com/")
"/path/to/file".toFileURL = NSURL(fileURLWithPath: "/path/to/file")Get the length of the String:
"123456789".length = 9Trim whitespace characters from String:
" 1 2 3 4 ".condenseWhiteSpace() = "1 2 3 4"Substring To, From, From to To, Range:
"0123456789".substringTo(5) = "01234"
"0123456789".substringFrom(5) = "56789"
"0123456789".substring(4, to: 7) = "456"Get the range of substring:
"0123456789".range("456") = NSRange(4, 3)Append path component:
"/folder/subfolder".stringByAppendingPathComponent("subfolder2/file") = "/folder/subfolder/subfolder2/file"Replace Characters with NSRange and return Value:
"0123456789".stringByReplacingCharactersInRange(NSMakeRange(4, 3), withString: "000") = "0123000789"Replace Characters with NSRange:
var string = "0123456789"
string.replaceCharactersInRange(NSMakeRange(4, 3), withString: "000") // string value will be "0123000789"Validate with regex:
"#hashtag".validate("#.*") = true
"#hashtag".validate("#.*")Find regex matches:
do
{
let array = try "name1 name2 name3".matches("[a-zA-Z]{4}[0-9]{1}") // array value will be ["name1", "name2", "name3"]
}
catch
{
// handle an error here
}Find ranges for values:
do
{
let array = try "name1 name2 name3".ranges("name") // array value will be [NSMakeRange(0, 4), NSMakeRange(6, 4), NSMakeRange(12, 4)]
}
catch
{
// handle an error here
}Get Characters and substrings via subscripts:
"123"[1] = Character("2") // Character value
"123"[1] = "2" // String value
"123"[NSMakeRange(1, 1)] = "2"
"123"[NSMakeRange(1, 1).toRange()!] = "2"Get visible string for rect:
let string = "string value here ..."
string.visibleStringInRect(CGRectValue, font: UIFontValue)Generate UUID:
String.UUID = "503bc59e-83f9-11e6-ae22-56b6b6499611" // value will be unique stringGet width for height and height for width:
"string value here".widthForHeight(50, font: UIFont())
"string value here".heightForWidth(50, font: UIFont())CGRect Extensions
Get and Set values for x, y, centerX, centerY, lastX, lastY, center, middle points from CGRect:
let frame = CGRectMake(10, 20, 50, 100)
frame.x = 10
frame.y = 20
frame.centerX = 30
frame.centerY = 60
frame.lastX = 60
frame.lastY = 120
frame.center = CGPointMake(30, 60)
frame.middle = CGPointMake(25, 50)CMTime Extensions
Convert CMTime to NSTimeInterval in seconds:
CMTimeMake(100, timescale: timescaleValue).toSeconds = 100AVPlayerItem Extensions
Get current playback time from AVPlayerItem:
let item = AVPlayerItem() // initialization here
item.currentPlaybackTime // value will be current playback time in secondsArray and Collection Extensions
Remove specific object from array:
var array = [1, 2, 3, 4, 5]
let removedObject = array.remove(2)
removedObject = 2
array = [1, 3, 4, 5]Insert contents of array at index:
var array1 = [1, 2, 3]
var array2 = [4, 5, 6]
let array3 = array1.insertContentsOf(array2, atIndex: 1)
array3 = [1, 4, 5, 6, 2, 3]Subscript two dimensional array with NSIndexPath:
let dataSource = [[1, 2], [3]]
dataSource[NSIndexPath(forRow: 0, inSection: 1)] = 3Remove object from two dimensional array with NSIndexPath:
let dataSource = [[1, 2], [3]]
let removedObject = dataSource.removeAtIndexPath(NSIndexPath(forRow: 0, inSection: 1))
removedObject = 3Convert String array to Int array:
let stringArray = ["1", "2", "3"]
stringArray.toInt = [1, 2, 3]NSObject Extensions
Get class full name as string:
UIViewController.stringFromClass = "ProjectTargetName.UIViewController"
UIViewController().stringFromClass = "ProjectTargetName.UIViewController"Get class name as string:
UIViewController.className = "UIViewController"
UIViewController().className = "UIViewController"Get Object from Nib:
NSObject.objectFromNib("NibName")
NSObject.objectFromNib("NibName", boundle: boundle, owner: owner, options: options)NSData Extensions
Download data from internet:
let url = NSURL(string: "https://avatars3.githubusercontent.com/u/5988751?v=3&s=466")!
let uuid = NSData.download(url, completeInMainThread: true, completion: { (data, id) in
id == uuid
data == downloaded data from url
})NSDate Extensions
Get local Date:
NSDate.localDate = current date by device timezoneCreate Date from day, month and year:
NSDate.dateWithDay(29, month: 7, year: 1992) = 29/07/1992Convert Date to String:
date.toString("dd-MM-YY") = "29-07-92"
date.toString("ss-mm-HH") = "27-35-11"Date properties:
let date = NSDate(timeIntervalSince1970: 1474647378)
let second = 18
let minute = 16
let hour = 18
let day = 23
let weekDay = 6
let weekdayOrdinal = 4
let month = 9
let year = 2016
let era = 1
self.date.second = second
self.date.minute = minute
self.date.hour = hour
self.date.day = day
self.date.weekDay = weekDay
self.date.weekdayOrdinal = weekdayOrdinal
self.date.month = month
self.date.year = year
self.date.era = eraNSDictionary Extensions
Get value for caseinsensitive key:
let dict = ["kEy" : "value"]
dict.valueForLowercaseKey("key") = "value"
dict.valueForLowercaseKey("KEY") = "value"NSURL Extensions
Exclude URL from icloud backup:
let url = NSURL(fileURLWithPath: "/path/to/file")
url.excludeFromBackup(true) // exclude
url.excludeFromBackup(false) // includeCheck if url is excluded from backup:
let url = NSURL(fileURLWithPath: "/path/to/file")
url.excludedFromBackup = true // excluded
url.excludedFromBackup = false // includedPHAsset Extensions
Check if PHAsset is already fetched from server:
let asset = PHAsset() // init here
asset.downloaded = true // fetched
asset.downloaded = false // not fetchedUIColor Extensions
Create UIColor with RGB integer and hex values:
UIColor(255, green: 0, blue: 0) // Red color
UIColor(hexValue: 0xff0000) // Red color
UIColor(hexString: "#ff0000") // Red colorGet color components:
let color = UIColor(1, green: 0.5, blue: 0)
color.red = 1
color.green = 0.5
color.blue = 0Get random color
UIColor.randomColorUIImage Extensions
Create image with color:
UIImage(color: UIColor.redColor(), size: CGSizeMake(100, 100))Download image from url:
let url = NSURL(string: "https://avatars3.githubusercontent.com/u/5988751?v=3&s=466")!
let uuid = UIImage.download(url, completion: { (image, id) in
id == uuid
image == downloaded image from url
})Animated image from GIF file:
UIImage.gif("file.gif") // gif with name
UIImage.gif(NSURL()) // gif with url
UIImage.gif(NSData()) // gif with data
UIImage.gif(CGImageSourceRef()) // gif with sourceInvert Transparancy:
let image = UIImage(named: "") // Init here
image.invertTransparancy()Get color with pixel:
let image = UIImage(named: "") // Init here
image.color(CGPointMake(20, 40))Resize Image:
let image = UIImage(named: "") // Init here
image.rescale(0.5) // image will be resized by 1/2
image.resize(CGSizeMake(10, 20)) // image will be resized on (10, 20) size
image.cutCircle(10) // image will cut circle with 10 radiusRotate Image:
let image = UIImage(named: "") // Init here
image.imageByRotation(90) // image will be rotated by 90 degreesChange orientation:
let image = UIImage(named: "") // Init here
image.changeOrientation(UIImageOrientation.Down) // image will have Down orientationUINib Extensions
Initialize nib:
UINib.instantiateType(type, nibName: name, bundle: boundle, owner: owner, options: options)UIView Extensions
Load view from nib:
UIView.loadNibNamed(nibName: String, nibClass: AnyClass)Get subviews by tag recursively:
self.view.subviews(27, recursively: true)Remove all subviews:
self.view.removeAllSubviews()Get screenshot from view:
self.view.screenshot() // returns UIImage
self.view.screenshot(CGRectMake(0, 0, 100, 100)) // returns UIImage from 0, 0, 100, 100 frameCovert View to Image:
self.view.toImageStretch view layout:
let view = UIView() // Init here
view.stretchLayout() // view will have the same frame as its superview
view.stretchLayout(UIView()) // view will have the same frame as another view
view.stretchLayout(UIView(), edgeInsets: UIEdgeInsetsMake()) // view will have the frame with insets to another viewGet constraints by identifier:
let view = UIView() // Init here
view.constraints("identifier") // returns array of NSLayoutConstraintMask view outside and inside of frame:
let view = UIView() // Init here
view.outterMask(CGRectMake(10, 10, 80, 80, cornerRadius: 10)) // cornerRadius is optional
view.innerMask(CGRectMake(10, 10, 80, 80, cornerRadius: 10)) // cornerRadius is optionalRemove mask from view:
view.removeMask()Check if view is masked:
view.masked = true // masked
view.masked = false // not maskedUIScrollView Extensions
Get and Set content width and height of scroll view:
scrollview.contentWidth = 100
scrollview.contentHeight = 100Check if scroll view is scroll top or bottom:
scrollview.scrolledTop = true // scrolled to top
scrollview.scrolledBottom = true // scrolled to bottomScroll scroll view to Top and Bottom:
scrollview.scrollToTop(true) // scroll to top with animation
scrollview.scrollToTop(false) // scroll to top without animation
scrollview.scrollToBottom(true) // scroll to top with animation
scrollview.scrollToBottom(false) // scroll to top without animationUIAlertView Extensions
Create simple alert view:
UIAlertView(title: String?, message: String, delegate: AnyObject?, tag: Int, style: UIAlertViewStyle, keyboardType: UIKeyboardType, cancelButtonTitle: String?, otherButtonTitles: String, String...)UIAlertController Extensions
Create simple alert controller:
UIAlertController(title: String?, message: String, style: UIAlertControllerStyle, inputFieldPlaceholders: [String], actionTitles: [String], actionBlocks: { (action) in
}, completion: {
})UIImageView Extensions
Create UIImageView with mask:
UIImageView.imageView(UIImage(), mask: UIImage())UILabel Extensions
Get width and height for label text by height, width and font:
label.widthForText
label.heightForTextTruncate label tail:
label.truncateTail(10, attributed: false) // truncate after 10 characters non attributed label
label.tailTruncated // check if label tail is truncated Get visible text rect:
label.textRect // return CGRectGet character index by point:
label.characterIndex(CGPointMake(10, 10)) // returns IntUITextField Extensions
Get width and height for text field text by height, width and font:
textField.widthForText
textField.heightForTextUITextView Extensions
Get width and height for text view text by height, width and font:
textView.widthForText
textView.heightForTextUIViewController Extensions
Load view controllers:
UIViewController.loadWithId("identifier", storyboard: "name") // storyboard name is optional. If it is not presented view controller will be loaded from Main storyboard
MyViewController.loadFromStoryboard("storyboardName") // storyboard name is optional. If it is not presented view controller will be loaded from Main storyboard
MyViewController.loadAsRootViewControllerFromStoryboard("storyboardName") // initializes viewcontroller and loads it as root. Storyboard name is optional. If it is not presented view controller will be loaded from Main storyboard
MyViewController().loadAsRootViewController() // loads view controller as root.MPMoviePlayerController Extensions
Get thumbnail from moview player:
player.thumbnail(CMTime) // returns UIImage. Time is optional. If it is not presented thumbnail will be loaded from the first frameInstallation
- Manually
- As Open Source:
- Download RDExtensionsSwift project
- Drag n drop the Source folder into your project (Make sure that you tick on Copy if needed checkbox)
- As Embedded Framework:
- Download RDExtensionsSwift project
- Build it for desired target
- Copy it into your project directory
- In Xcode navigator select project >> General >> Embedded Binaries: click + button and select RDExtensionsSwift framework.
source 'https://github.com/CocoaPods/Specs.git'
use_frameworks!
target 'ProjectName' do
# For latest version:
pod 'RDExtensionsSwift'
# For earlier verions:
pod 'RDExtensionsSwift', '~> 5.0.1' # for Swift 5.0
pod 'RDExtensionsSwift', '~> 4.2.3' # for Swift 4.2
pod 'RDExtensionsSwift', '~> 4.0.1' # for Swift 4
pod 'RDExtensionsSwift', '~> 3.1.1' # for Swift 3.2
pod 'RDExtensionsSwift', '~> 2.1.0' # for Swift 3.0
pod 'RDExtensionsSwift', '~> 1.0.7' # for Swift 2
endRun pod install, and you should now have the latest RDExtensionsSwift release.
Usage
All you need to do is to import the library and start coding:
import RDExtensionsSwiftRequirements
- Swift 2.2 or later
Author
Giorgi Iashvili, [email protected]
License
RDExtensionsSwift is available under the MIT license. See the LICENSE file for more info.