Swift 3 support for Xcode 8 + all tests

This commit is contained in:
Olexii Pyvovarov 2016-09-20 01:48:19 +03:00
parent 6e856a91ab
commit 201850843f
51 changed files with 781 additions and 751 deletions

View File

@ -596,14 +596,16 @@
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 0730;
LastUpgradeCheck = 0710;
LastUpgradeCheck = 0800;
ORGANIZATIONNAME = "Goktug Yilmaz";
TargetAttributes = {
B5DC86A81C0ED06700972D0A = {
CreatedOnToolsVersion = 7.1;
LastSwiftMigration = 0800;
};
B5DC86B21C0ED06700972D0A = {
CreatedOnToolsVersion = 7.1;
LastSwiftMigration = 0800;
};
};
};
@ -933,8 +935,10 @@
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
@ -979,8 +983,10 @@
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
@ -999,6 +1005,7 @@
GCC_WARN_UNUSED_VARIABLE = YES;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
VALIDATE_PRODUCT = YES;
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
@ -1008,6 +1015,7 @@
B5DC86BE1C0ED06700972D0A /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "";
DEFINES_MODULE = YES;
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1.0.2;
@ -1019,6 +1027,7 @@
PRODUCT_BUNDLE_IDENTIFIER = com.gbf.EZSwiftExtensions.EZSwiftExtensions;
PRODUCT_NAME = EZSwiftExtensions;
SKIP_INSTALL = YES;
SWIFT_VERSION = 3.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
@ -1026,6 +1035,7 @@
B5DC86BF1C0ED06700972D0A /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "";
DEFINES_MODULE = YES;
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1.0.2;
@ -1037,6 +1047,7 @@
PRODUCT_BUNDLE_IDENTIFIER = com.gbf.EZSwiftExtensions.EZSwiftExtensions;
PRODUCT_NAME = EZSwiftExtensions;
SKIP_INSTALL = YES;
SWIFT_VERSION = 3.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
@ -1048,6 +1059,7 @@
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.gbf.EZSwiftExtensions.EZSwiftExtensionsTests;
PRODUCT_NAME = EZSwiftExtensionsTest;
SWIFT_VERSION = 3.0;
};
name = Debug;
};
@ -1058,12 +1070,14 @@
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.gbf.EZSwiftExtensions.EZSwiftExtensionsTests;
PRODUCT_NAME = EZSwiftExtensionsTest;
SWIFT_VERSION = 3.0;
};
name = Release;
};
CD4D30E11CEEAFD900CB53BC /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
"CODE_SIGN_IDENTITY[sdk=appletvos*]" = "";
DEFINES_MODULE = YES;
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1.0.2;
@ -1082,6 +1096,7 @@
CD4D30E21CEEAFD900CB53BC /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
"CODE_SIGN_IDENTITY[sdk=appletvos*]" = "";
DEFINES_MODULE = YES;
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1.0.2;

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0710"
LastUpgradeVersion = "0800"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"

View File

@ -126,13 +126,14 @@ class ArrayTests: XCTestCase {
XCTAssertEqual(difference, [0, 5, 6, 7, 8])
}
/// WARNING: [SE-0121] Remove Optional Comparison Operators
func testOptionalEquatable() {
let a: [Int]? = [1, 2, 3]
let b: [Int]? = [1, 2, 3]
let c: [Int]? = nil
// let c: [Int]? = nil
XCTAssertTrue(a == b)
XCTAssertFalse(a == c)
XCTAssertTrue(a! == b!)
// XCTAssertFalse(a! == c!)
}
func testShuffle() {
@ -144,8 +145,8 @@ class ArrayTests: XCTestCase {
XCTAssertEqual(numberArray.count, copyArray.count)
for e in copyArray {
if let i = numberArray.indexOf(e) {
numberArray.removeAtIndex(i)
if let i = numberArray.index(of: e) {
numberArray.remove(at: i)
}
}
XCTAssertEqual(numberArray, [])

View File

@ -59,11 +59,11 @@ class DictionaryTests: XCTestCase {
func testToArray() {
let array = fourthDic.toArray { key, value in
return key.uppercaseString + String(value)
return key.uppercased() + String(value)
}
XCTAssertNotNil(array.indexOf("TWO2"))
XCTAssertNotNil(array.indexOf("FIVE5"))
XCTAssertNotNil(array.index(of: "TWO2"))
XCTAssertNotNil(array.index(of: "FIVE5"))
XCTAssertEqual(array.count, fourthDic.count)
}
@ -90,7 +90,7 @@ class DictionaryTests: XCTestCase {
}
func testJSON () {
let jsonDic = NSDictionary(dictionary: ["name": "John", "surname": "Smith", "age": 35.0, "married": NSNumber.init(bool: true), "children": 3])
let jsonDic = NSDictionary(dictionary: ["name": "John", "surname": "Smith", "age": 35.0, "married": NSNumber.init(value: true as Bool), "children": 3])
let jsonString = jsonDic.formatJSON()
XCTAssertNotNil(jsonString)
let secondJsonDic = NSDictionary(json: jsonString!)

View File

@ -20,7 +20,7 @@ class EZSwiftFunctionsTests: XCTestCase {
}
var totalValue = 0
var totalLoopCount = 0
for e in ez.iterateEnum(testEnum) {
for e in ez.iterateEnum(testEnum.self) {
totalValue += e.rawValue
totalLoopCount += 1
}

View File

@ -28,7 +28,7 @@ class EZSwiftExtensionsTests: XCTestCase {
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
self.measure {
// Put the code you want to measure the time of here.
}
}

View File

@ -7,6 +7,17 @@
//
import XCTest
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
class NSDateTests: XCTestCase {
// note that NSDate uses UTC in NSDate(timeIntervalSince1970: _)
@ -22,37 +33,37 @@ class NSDateTests: XCTestCase {
}
func testDateFromString() {
guard let dateFromString = NSDate(fromString: string, format: format) else {
guard let dateFromString = Date(fromString: string, format: format) else {
XCTFail("Date From String Couldn't be initialized.")
return
}
let formatter = NSDateFormatter()
let formatter = DateFormatter()
formatter.dateFormat = format
let dateString = formatter.dateFromString(string)
let dateString = formatter.date(from: string)
XCTAssertEqual(dateFromString, dateString)
XCTAssertNil(NSDate(fromString: wrongDateString, format: format), "Date From String initialized, but source string was invalid.")
XCTAssertNil(Date(fromString: wrongDateString, format: format), "Date From String initialized, but source string was invalid.")
}
func testDateToString() {
let date = NSDate(timeIntervalSince1970: 0)
let date = Date(timeIntervalSince1970: 0)
let formatter = NSDateFormatter()
let formatter = DateFormatter()
formatter.dateFormat = format
let dateString = formatter.stringFromDate(date)
let dateString = formatter.string(from: date)
XCTAssertEqual(date.toString(format: format), dateString)
}
func testTimePassedBetweenDates() {
let date = NSDate(timeIntervalSince1970: 0)
XCTAssertTrue(date.timePassed().containsString("years"))
let now = NSDate()
XCTAssertTrue(now.timePassed().containsString("now") || now.timePassed().containsString("seconds"))
let date = Date(timeIntervalSince1970: 0)
XCTAssertTrue(date.timePassed().contains("years"))
let now = Date()
XCTAssertTrue(now.timePassed().contains("now") || now.timePassed().contains("seconds"))
}
func testComparable() {
let date = NSDate()
let future = NSDate(timeIntervalSinceNow: 1000)
let date = Date()
let future = Date(timeIntervalSinceNow: 1000)
XCTAssertTrue(date < future)
XCTAssertFalse(date > future)
XCTAssertTrue(date == date)

View File

@ -11,7 +11,7 @@ import XCTest
class NSURLTests: XCTestCase {
func testQueryParameters() {
let url = NSURL(string: "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=facebook")
let url = URL(string: "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=facebook")
if let queryParameters = url?.queryParameters {
XCTAssertEqual(queryParameters["v"], Optional("1.0"))
XCTAssertEqual(queryParameters["q"], Optional("facebook"))
@ -22,27 +22,27 @@ class NSURLTests: XCTestCase {
func testRemote() {
var len: Int64?
var support: Bool?
let urlResume = NSURL(string: "http://httpbin.org/range/1024")!
let urlSize = NSURL(string: "http://httpbin.org/bytes/1024")!
let group = dispatch_group_create()
dispatch_group_enter(group)
let urlResume = URL(string: "http://httpbin.org/range/1024")!
let urlSize = URL(string: "http://httpbin.org/bytes/1024")!
let group = DispatchGroup()
group.enter()
urlSize.remoteSize({ (contentLength: Int64) in
len = contentLength
dispatch_group_leave(group)
group.leave()
})
dispatch_group_enter(group)
group.enter()
urlResume.supportsResume({ (doesSupport: Bool) in
support = doesSupport
dispatch_group_leave(group)
group.leave()
})
dispatch_group_wait(group, dispatch_time(DISPATCH_TIME_NOW, Int64(30 * NSEC_PER_SEC)))
_ = group.wait(timeout: DispatchTime.now() + Double(Int64(30 * NSEC_PER_SEC)) / Double(NSEC_PER_SEC))
XCTAssertEqual(len, 1024)
XCTAssertEqual(support, true)
}
func testIsSame() {
let url1 = NSURL(string: "http://google.com/")!
let url2 = NSURL(string: "http://www.google.com")!
let url1 = URL(string: "http://google.com/")!
let url2 = URL(string: "http://www.google.com")!
XCTAssertTrue(url1.isSameWithURL(url2))
}

View File

@ -20,7 +20,7 @@ class StringTests: XCTestCase {
func testSubscript() {
XCTAssertEqual(string[2], "2")
XCTAssertEqual(string[9], "9")
XCTAssertEqual(string[0...9], "0123456789")
XCTAssertEqual(string[0..<10], "0123456789")
XCTAssertEqual(string[3..<5], "34")
}
@ -146,8 +146,8 @@ class StringTests: XCTestCase {
func testContains() {
XCTAssertTrue(string.contains("01"))
XCTAssertTrue(string.contains("01", compareOption: NSStringCompareOptions.AnchoredSearch))
XCTAssertFalse(string.contains("12", compareOption: NSStringCompareOptions.AnchoredSearch))
XCTAssertTrue(string.contains("01", compareOption: NSString.CompareOptions.anchored))
XCTAssertFalse(string.contains("12", compareOption: NSString.CompareOptions.anchored))
XCTAssertFalse(string.contains("h"))
}
@ -158,7 +158,7 @@ class StringTests: XCTestCase {
XCTAssertNotNil(string.toFloat())
XCTAssertEqual(String(10.253, precision: 2), "10.25")
XCTAssertEqual(String(10.257, precision: 2), "10.26")
XCTAssertTrue(string.toNSString.isKindOfClass(NSString.self))
XCTAssertTrue(string.toNSString.isKind(of: NSString.self))
}
func testIsIncludeEmoji() {

View File

@ -16,23 +16,23 @@ class UIColorTests: XCTestCase {
override func setUp() {
super.setUp()
color = UIColor.blueColor()
color = UIColor.blue
}
func testInitRGBValues() {
color = UIColor(r: 255, g: 255, b: 255)
let red = CGColorGetComponents(color.CGColor)[0]
let red = color.cgColor.components?[0]
XCTAssertEqual(red, 1)
}
func testInitHexString() {
color = UIColor(hexString: "ff0000")
let red = CGColorGetComponents(color.CGColor)[0]
let green = CGColorGetComponents(color.CGColor)[1]
let blue = CGColorGetComponents(color.CGColor)[2]
let red = color.cgColor.components?[0]
let green = color.cgColor.components?[1]
let blue = color.cgColor.components?[2]
XCTAssertEqual(red, 1)
XCTAssertEqual(blue, 0)
@ -40,13 +40,12 @@ class UIColorTests: XCTestCase {
}
func testInitGray() {
color = UIColor(gray: 100)
let red = CGColorGetComponents(color.CGColor)[0]
let green = CGColorGetComponents(color.CGColor)[1]
let blue = CGColorGetComponents(color.CGColor)[2]
var red : CGFloat = 0
var green : CGFloat = 0
var blue : CGFloat = 0
XCTAssertTrue(color.getRed(&red, green: &green, blue: &blue, alpha: nil))
let gray = Double(0.299 * red + 0.587 * green + 0.114 * blue).getRoundedByPlaces(7)
let testGray = (100 / 255).getRoundedByPlaces(7)
XCTAssertEqual(gray, testGray)
@ -54,21 +53,21 @@ class UIColorTests: XCTestCase {
func testRedComponent() {
color = UIColor.redColor()
color = UIColor.red
XCTAssertEqual(color.redComponent, 255)
}
func testGreenComponent() {
color = UIColor.greenColor()
color = UIColor.green
XCTAssertEqual(color.greenComponent, 255)
}
func testBlueComponent() {
color = UIColor.blueColor()
color = UIColor.blue
XCTAssertEqual(color.blueComponent, 255)
}

View File

@ -6,6 +6,26 @@
// Copyright (c) 2015 Goktug Yilmaz. All rights reserved.
//
import UIKit
fileprivate func < <T: Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
fileprivate func >= <T: Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l >= r
default:
return !(lhs < rhs)
}
}
extension Array {
/// EZSE: Returns a random element from the array.
@ -19,9 +39,9 @@ extension Array {
}
/// EZSE: Checks if array contains at least 1 instance of the given object type
public func containsInstanceOf<T>(object: T) -> Bool {
public func containsInstanceOf<T>(_ object: T) -> Bool {
for item in self {
if item.dynamicType == object.dynamicType {
if type(of: item) == type(of: object) {
return true
}
}
@ -29,7 +49,7 @@ extension Array {
}
/// EZSE: Checks if test returns true for all the elements in self
public func testAll(test: (Element) -> Bool) -> Bool {
public func testAll(_ test: (Element) -> Bool) -> Bool {
for item in self {
if !test(item) {
return false
@ -39,7 +59,7 @@ extension Array {
}
/// EZSE: Checks if all elements in the array are true of false
public func testIfAllIs(condition: Bool) -> Bool {
public func testIfAllIs(_ condition: Bool) -> Bool {
for item in self {
guard let item = item as? Bool else { return false }
@ -51,46 +71,46 @@ extension Array {
}
/// EZSE: Gets the object at the specified index, if it exists.
public func get(index: Int) -> Element? {
public func get(_ index: Int) -> Element? {
return index >= 0 && index < count ? self[index] : nil
}
/// EZSE: Reverse the given index. i.g.: reverseIndex(2) would be 2 to the last
public func reverseIndex(index: Int) -> Int {
public func reverseIndex(_ index: Int) -> Int {
return Swift.max(self.count - 1 - index, 0)
}
/// EZSE: Returns an array with the given number as the max number of elements.
public func takeMax(n: Int) -> Array {
public func takeMax(_ n: Int) -> Array {
return Array(self[0..<Swift.max(0, Swift.min(n, count))])
}
/// EZSE: Iterates on each element of the array.
@available(*, deprecated=1.6)
public func each(call: (Element) -> ()) {
@available(*, deprecated: 1.6)
public func each(_ call: (Element) -> ()) {
for item in self {
call(item)
}
}
/// EZSE: Iterates on each element of the array with its index. (Index, Element)
@available(*, deprecated=1.6, renamed="forEach")
public func each(call: (Int, Element) -> ()) {
for (index, item) in self.enumerate() {
@available(*, deprecated: 1.6, renamed: "forEach")
public func each(_ call: (Int, Element) -> ()) {
for (index, item) in self.enumerated() {
call(index, item)
}
}
/// EZSE: Iterates on each element of the array with its index. (Index, Element)
public func forEach(call: (Int, Element) -> ()) {
for (index, item) in self.enumerate() {
public func forEach(_ call: (Int, Element) -> ()) {
for (index, item) in self.enumerated() {
call(index, item)
}
}
/// EZSE: Creates an array with values generated by running each value of self
/// through the mapFunction and discarding nil return values.
@available(*, deprecated=1.6, renamed="flatMap")
@available(*, deprecated: 1.6, renamed: "flatMap")
public func mapFilter<V>(mapFunction map: (Element) -> (V)?) -> [V] {
var mapped = [V]()
forEach { (value: Element) -> Void in
@ -102,8 +122,8 @@ extension Array {
}
/// EZSE: Prepends an object to the array.
public mutating func insertAsFirst(newElement: Element) {
insert(newElement, atIndex: 0)
public mutating func insertAsFirst(_ newElement: Element) {
insert(newElement, at: 0)
}
/// EZSE: Shuffles the array in-place using the Fisher-Yates-Durstenfeld algorithm.
@ -117,7 +137,7 @@ extension Array {
}
/// EZSE: Decompose an array to a tuple with first element and the rest; useful in Functional Programming
public func decompose() -> (head: Generator.Element, tail: SubSequence)? {
public func decompose() -> (head: Iterator.Element, tail: SubSequence)? {
return (count > 0) ? (self[0], self[1..<count]) : nil
}
@ -126,7 +146,7 @@ extension Array {
extension Array where Element: Equatable {
/// EZSE: Returns the indexes of the object
public func indexesOf(object: Element) -> [Int] {
public func indexesOf(_ object: Element) -> [Int] {
var indexes = [Int]()
for index in 0..<self.count {
if self[index] == object {
@ -137,17 +157,17 @@ extension Array where Element: Equatable {
}
/// EZSE: Returns the last index of the object
public func lastIndexOf(object: Element) -> Int? {
public func lastIndexOf(_ object: Element) -> Int? {
return indexesOf(object).last
}
/// EZSE: Checks if self contains a list of items.
public func contains(items: Element...) -> Bool {
return items.testAll { self.indexOf($0) >= 0 }
public func contains(_ items: Element...) -> Bool {
return items.testAll { self.index(of: $0) >= 0 }
}
/// EZSE: Difference of self and the input arrays.
public func difference(values: [Element]...) -> [Element] {
public func difference(_ values: [Element]...) -> [Element] {
var result = [Element]()
elements: for element in self {
for value in values {
@ -164,11 +184,11 @@ extension Array where Element: Equatable {
}
/// EZSE: Intersection of self and the input arrays.
public func intersection(values: [Element]...) -> Array {
public func intersection(_ values: [Element]...) -> Array {
var result = self
var intersection = Array()
for (i, value) in values.enumerate() {
for (i, value) in values.enumerated() {
// the intersection is computed by intersecting a couple per loop:
// self n values[0], (self n values[0]) n values[1], ...
if i > 0 {
@ -188,7 +208,7 @@ extension Array where Element: Equatable {
}
/// EZSE: Union of self and the input arrays.
public func union(values: [Element]...) -> Array {
public func union(_ values: [Element]...) -> Array {
var result = self
for array in values {
for value in array {
@ -201,21 +221,21 @@ extension Array where Element: Equatable {
}
/// EZSE: Removes the first given object
public mutating func removeObject(object: Element) {
if let index = self.indexOf(object) {
self.removeAtIndex(index)
public mutating func removeObject(_ object: Element) {
if let index = self.index(of: object) {
self.remove(at: index)
}
}
/// EZSE: Removes all occurrences of the given object
public mutating func removeObjects(object: Element) {
for i in self.indexesOf(object).reverse() {
self.removeAtIndex(i)
public mutating func removeObjects(_ object: Element) {
for i in self.indexesOf(object).reversed() {
self.remove(at: i)
}
}
/// EZSE: Checks if the main array contains the parameter array
public func containsArray(lookFor: [Element]) -> Bool {
public func containsArray(_ lookFor: [Element]) -> Bool {
for item in lookFor {
if self.contains(item) == false {
return false
@ -227,9 +247,9 @@ extension Array where Element: Equatable {
public func ==<T: Equatable>(lhs: [T]?, rhs: [T]?) -> Bool {
switch (lhs, rhs) {
case (.Some(let lhs), .Some(let rhs)):
case (.some(let lhs), .some(let rhs)):
return lhs == rhs
case (.None, .None):
case (.none, .none):
return true
default:
return false

View File

@ -7,14 +7,14 @@
//
import UIKit
public typealias BlockButtonAction = (sender: BlockButton) -> Void
public typealias BlockButtonAction = (_ sender: BlockButton) -> Void
///Make sure you use "[weak self] (sender) in" if you are using the keyword self inside the closure or there might be a memory leak
public class BlockButton: UIButton {
open class BlockButton: UIButton {
// MARK: Propeties
public var highlightLayer: CALayer?
public var action: BlockButtonAction?
open var highlightLayer: CALayer?
open var action: BlockButtonAction?
// MARK: Init
@ -34,7 +34,7 @@ public class BlockButton: UIButton {
defaultInit()
}
public init(action: BlockButtonAction) {
public init(action: @escaping BlockButtonAction) {
super.init(frame: CGRect.zero)
self.action = action
defaultInit()
@ -45,7 +45,7 @@ public class BlockButton: UIButton {
defaultInit()
}
public init(frame: CGRect, action: BlockButtonAction) {
public init(frame: CGRect, action: @escaping BlockButtonAction) {
super.init(frame: frame)
self.action = action
defaultInit()
@ -56,55 +56,55 @@ public class BlockButton: UIButton {
defaultInit()
}
private func defaultInit() {
addTarget(self, action: #selector(BlockButton.didPressed(_:)), forControlEvents: UIControlEvents.TouchUpInside)
addTarget(self, action: #selector(BlockButton.highlight), forControlEvents: [UIControlEvents.TouchDown, UIControlEvents.TouchDragEnter])
addTarget(self, action: #selector(BlockButton.unhighlight), forControlEvents: [
UIControlEvents.TouchUpInside,
UIControlEvents.TouchUpOutside,
UIControlEvents.TouchCancel,
UIControlEvents.TouchDragExit
fileprivate func defaultInit() {
addTarget(self, action: #selector(BlockButton.didPressed(_:)), for: UIControlEvents.touchUpInside)
addTarget(self, action: #selector(BlockButton.highlight), for: [UIControlEvents.touchDown, UIControlEvents.touchDragEnter])
addTarget(self, action: #selector(BlockButton.unhighlight), for: [
UIControlEvents.touchUpInside,
UIControlEvents.touchUpOutside,
UIControlEvents.touchCancel,
UIControlEvents.touchDragExit
])
setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
setTitleColor(UIColor.blueColor(), forState: UIControlState.Selected)
setTitleColor(UIColor.black, for: UIControlState())
setTitleColor(UIColor.blue, for: UIControlState.selected)
}
public func addAction(action: BlockButtonAction) {
open func addAction(_ action: @escaping BlockButtonAction) {
self.action = action
}
// MARK: Action
public func didPressed(sender: BlockButton) {
action?(sender: sender)
open func didPressed(_ sender: BlockButton) {
action?(sender)
}
// MARK: Highlight
public func highlight() {
open func highlight() {
if action == nil {
return
}
let highlightLayer = CALayer()
highlightLayer.frame = layer.bounds
highlightLayer.backgroundColor = UIColor.blackColor().CGColor
highlightLayer.backgroundColor = UIColor.black.cgColor
highlightLayer.opacity = 0.5
var maskImage: UIImage? = nil
UIGraphicsBeginImageContextWithOptions(layer.bounds.size, false, 0)
if let context = UIGraphicsGetCurrentContext() {
layer.renderInContext(context)
layer.render(in: context)
maskImage = UIGraphicsGetImageFromCurrentImageContext()
}
UIGraphicsEndImageContext()
let maskLayer = CALayer()
maskLayer.contents = maskImage?.CGImage
maskLayer.contents = maskImage?.cgImage
maskLayer.frame = highlightLayer.frame
highlightLayer.mask = maskLayer
layer.addSublayer(highlightLayer)
self.highlightLayer = highlightLayer
}
public func unhighlight() {
open func unhighlight() {
if action == nil {
return
}

View File

@ -9,10 +9,10 @@
import UIKit
///Make sure you use "[weak self] (gesture) in" if you are using the keyword self inside the closure or there might be a memory leak
public class BlockLongPress: UILongPressGestureRecognizer {
private var longPressAction: ((UILongPressGestureRecognizer) -> Void)?
open class BlockLongPress: UILongPressGestureRecognizer {
fileprivate var longPressAction: ((UILongPressGestureRecognizer) -> Void)?
public override init(target: AnyObject?, action: Selector) {
public override init(target: Any?, action: Selector?) {
super.init(target: target, action: action)
}
@ -22,8 +22,8 @@ public class BlockLongPress: UILongPressGestureRecognizer {
addTarget(self, action: #selector(BlockLongPress.didLongPressed(_:)))
}
public func didLongPressed(longPress: UILongPressGestureRecognizer) {
if longPress.state == UIGestureRecognizerState.Began {
open func didLongPressed(_ longPress: UILongPressGestureRecognizer) {
if longPress.state == UIGestureRecognizerState.began {
longPressAction?(longPress)
}
}

View File

@ -9,10 +9,10 @@
import UIKit
///Make sure you use "[weak self] (gesture) in" if you are using the keyword self inside the closure or there might be a memory leak
public class BlockPan: UIPanGestureRecognizer {
private var panAction: ((UIPanGestureRecognizer) -> Void)?
open class BlockPan: UIPanGestureRecognizer {
fileprivate var panAction: ((UIPanGestureRecognizer) -> Void)?
public override init(target: AnyObject?, action: Selector) {
public override init(target: Any?, action: Selector?) {
super.init(target: target, action: action)
}
@ -22,7 +22,7 @@ public class BlockPan: UIPanGestureRecognizer {
self.addTarget(self, action: #selector(BlockPan.didPan(_:)))
}
public func didPan (pan: UIPanGestureRecognizer) {
open func didPan (_ pan: UIPanGestureRecognizer) {
panAction? (pan)
}
}

View File

@ -11,10 +11,10 @@ import UIKit
#if os(iOS)
///Make sure you use "[weak self] (gesture) in" if you are using the keyword self inside the closure or there might be a memory leak
public class BlockPinch: UIPinchGestureRecognizer {
private var pinchAction: ((UIPinchGestureRecognizer) -> Void)?
open class BlockPinch: UIPinchGestureRecognizer {
fileprivate var pinchAction: ((UIPinchGestureRecognizer) -> Void)?
public override init(target: AnyObject?, action: Selector) {
public override init(target: Any?, action: Selector?) {
super.init(target: target, action: action)
}
@ -24,7 +24,7 @@ public class BlockPinch: UIPinchGestureRecognizer {
self.addTarget(self, action: #selector(BlockPinch.didPinch(_:)))
}
public func didPinch (pinch: UIPinchGestureRecognizer) {
open func didPinch (_ pinch: UIPinchGestureRecognizer) {
pinchAction? (pinch)
}
}

View File

@ -9,10 +9,10 @@
import UIKit
///Make sure you use "[weak self] (gesture) in" if you are using the keyword self inside the closure or there might be a memory leak
public class BlockSwipe: UISwipeGestureRecognizer {
private var swipeAction: ((UISwipeGestureRecognizer) -> Void)?
open class BlockSwipe: UISwipeGestureRecognizer {
fileprivate var swipeAction: ((UISwipeGestureRecognizer) -> Void)?
public override init(target: AnyObject?, action: Selector) {
public override init(target: Any?, action: Selector?) {
super.init(target: target, action: action)
}
@ -32,7 +32,7 @@ public class BlockSwipe: UISwipeGestureRecognizer {
addTarget(self, action: #selector(BlockSwipe.didSwipe(_:)))
}
public func didSwipe (swipe: UISwipeGestureRecognizer) {
open func didSwipe (_ swipe: UISwipeGestureRecognizer) {
swipeAction? (swipe)
}
}

View File

@ -9,10 +9,10 @@
import UIKit
///Make sure you use "[weak self] (gesture) in" if you are using the keyword self inside the closure or there might be a memory leak
public class BlockTap: UITapGestureRecognizer {
private var tapAction: ((UITapGestureRecognizer) -> Void)?
open class BlockTap: UITapGestureRecognizer {
fileprivate var tapAction: ((UITapGestureRecognizer) -> Void)?
public override init(target: AnyObject?, action: Selector) {
public override init(target: Any?, action: Selector?) {
super.init(target: target, action: action)
}
@ -33,7 +33,7 @@ public class BlockTap: UITapGestureRecognizer {
self.addTarget(self, action: #selector(BlockTap.didTap(_:)))
}
public func didTap (tap: UITapGestureRecognizer) {
open func didTap (_ tap: UITapGestureRecognizer) {
tapAction? (tap)
}
}

View File

@ -11,12 +11,12 @@ import UIKit
#if os(iOS)
///Make sure you use `[weak self] (NSURLRequest) in` if you are using the keyword `self` inside the closure or there might be a memory leak
public class BlockWebView: UIWebView, UIWebViewDelegate {
public var didStartLoad: ((NSURLRequest) -> ())?
public var didFinishLoad: ((NSURLRequest) -> ())?
public var didFailLoad: ((NSURLRequest, NSError) -> ())?
open class BlockWebView: UIWebView, UIWebViewDelegate {
open var didStartLoad: ((URLRequest) -> ())?
open var didFinishLoad: ((URLRequest) -> ())?
open var didFailLoad: ((URLRequest, NSError) -> ())?
public var shouldStartLoadingRequest: ((NSURLRequest) -> (Bool))?
open var shouldStartLoadingRequest: ((URLRequest) -> (Bool))?
public override init(frame: CGRect) {
super.init(frame: frame)
@ -28,19 +28,19 @@ public class BlockWebView: UIWebView, UIWebViewDelegate {
}
public func webViewDidStartLoad(webView: UIWebView) {
open func webViewDidStartLoad(_ webView: UIWebView) {
didStartLoad? (webView.request!)
}
public func webViewDidFinishLoad(webView: UIWebView) {
open func webViewDidFinishLoad(_ webView: UIWebView) {
didFinishLoad? (webView.request!)
}
public func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
didFailLoad? (webView.request!, error!)
open func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
didFailLoad? (webView.request!, error as NSError)
}
public func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
open func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if let should = shouldStartLoadingRequest {
return should (request)
} else {

View File

@ -8,9 +8,10 @@
extension Bool {
/// EZSE: Converts Bool to Int.
public var toInt: Int { return Int(self) }
public var toInt: Int { return self ? 1 : 0 }
/// EZSE: Toggle boolean value.
@discardableResult
public mutating func toggle() -> Bool {
self = !self
return self

View File

@ -28,7 +28,7 @@ extension CGFloat {
}
/// EZSE: Converts angle degrees to radians.
public static func degreesToRadians(angle: CGFloat) -> CGFloat {
public static func degreesToRadians(_ angle: CGFloat) -> CGFloat {
return (CGFloat (M_PI) * angle) / 180.0
}
}

View File

@ -15,7 +15,7 @@ extension Dictionary {
}
/// EZSE: Union of self and the input dictionaries.
public func union(dictionaries: Dictionary...) -> Dictionary {
public func union(_ dictionaries: Dictionary...) -> Dictionary {
var result = self
dictionaries.forEach { (dictionary) -> Void in
dictionary.forEach { (key, value) -> Void in
@ -27,10 +27,10 @@ extension Dictionary {
/// EZSE: Intersection of self and the input dictionaries.
/// Two dictionaries are considered equal if they contain the same [key: value] copules.
public func intersection<K, V where K: Equatable, V: Equatable>(dictionaries: [K: V]...) -> [K: V] {
public func intersection<K, V>(_ dictionaries: [K: V]...) -> [K: V] where K: Equatable, V: Equatable {
// Casts self from [Key: Value] to [K: V]
let filtered = mapFilter { (item, value) -> (K, V)? in
if let item = item as? K, value = value as? V {
if let item = item as? K, let value = value as? V {
return (item, value)
}
return nil
@ -44,13 +44,13 @@ extension Dictionary {
}
/// EZSE: Checks if a key exists in the dictionary.
public func has(key: Key) -> Bool {
return indexForKey(key) != nil
public func has(_ key: Key) -> Bool {
return index(forKey: key) != nil
}
/// EZSE: Creates an Array with values generated by running
/// each [key: value] of self through the mapFunction.
public func toArray<V>(map: (Key, Value) -> V) -> [V] {
public func toArray<V>(_ map: (Key, Value) -> V) -> [V] {
var mapped: [V] = []
forEach {
mapped.append(map($0, $1))
@ -60,7 +60,7 @@ extension Dictionary {
/// EZSE: Creates a Dictionary with the same keys as self and values generated by running
/// each [key: value] of self through the mapFunction.
public func mapValues<V>(map: (Key, Value) -> V) -> [Key: V] {
public func mapValues<V>(_ map: (Key, Value) -> V) -> [Key: V] {
var mapped: [Key: V] = [:]
forEach {
mapped[$0] = map($0, $1)
@ -70,7 +70,7 @@ extension Dictionary {
/// EZSE: Creates a Dictionary with the same keys as self and values generated by running
/// each [key: value] of self through the mapFunction discarding nil return values.
public func mapFilterValues<V>(map: (Key, Value) -> V?) -> [Key: V] {
public func mapFilterValues<V>(_ map: (Key, Value) -> V?) -> [Key: V] {
var mapped: [Key: V] = [:]
forEach {
if let value = map($0, $1) {
@ -82,7 +82,7 @@ extension Dictionary {
/// EZSE: Creates a Dictionary with keys and values generated by running
/// each [key: value] of self through the mapFunction discarding nil return values.
public func mapFilter<K, V>(map: (Key, Value) -> (K, V)?) -> [K: V] {
public func mapFilter<K, V>(_ map: (Key, Value) -> (K, V)?) -> [K: V] {
var mapped: [K: V] = [:]
forEach {
if let value = map($0, $1) {
@ -94,7 +94,7 @@ extension Dictionary {
/// EZSE: Creates a Dictionary with keys and values generated by running
/// each [key: value] of self through the mapFunction.
public func map<K, V>(map: (Key, Value) -> (K, V)) -> [K: V] {
public func map<K, V>(_ map: (Key, Value) -> (K, V)) -> [K: V] {
var mapped: [K: V] = [:]
forEach {
let (_key, _value) = map($0, $1)
@ -105,7 +105,7 @@ extension Dictionary {
/// EZSE: Constructs a dictionary containing every [key: value] pair from self
/// for which testFunction evaluates to true.
public func filter(test: (Key, Value) -> Bool) -> Dictionary {
public func filter(_ test: (Key, Value) -> Bool) -> Dictionary {
var result = Dictionary()
for (key, value) in self {
if test(key, value) {
@ -116,7 +116,7 @@ extension Dictionary {
}
/// EZSE: Checks if test evaluates true for all the elements in self.
public func testAll(test: (Key, Value) -> (Bool)) -> Bool {
public func testAll(_ test: (Key, Value) -> (Bool)) -> Bool {
for (key, value) in self {
if !test(key, value) {
return false
@ -129,12 +129,12 @@ extension Dictionary {
extension Dictionary where Value: Equatable {
/// EZSE: Difference of self and the input dictionaries.
/// Two dictionaries are considered equal if they contain the same [key: value] pairs.
public func difference(dictionaries: [Key: Value]...) -> [Key: Value] {
public func difference(_ dictionaries: [Key: Value]...) -> [Key: Value] {
var result = self
for dictionary in dictionaries {
for (key, value) in dictionary {
if result.has(key) && result[key] == value {
result.removeValueForKey(key)
result.removeValue(forKey: key)
}
}
}
@ -143,7 +143,7 @@ extension Dictionary where Value: Equatable {
}
/// EZSE: Combines the first dictionary with the second and returns single dictionary
public func += <KeyType, ValueType> (inout left: Dictionary<KeyType, ValueType>, right: Dictionary<KeyType, ValueType>) {
public func += <KeyType, ValueType> (left: inout Dictionary<KeyType, ValueType>, right: Dictionary<KeyType, ValueType>) {
for (k, v) in right {
left.updateValue(v, forKey: k)
}

View File

@ -18,26 +18,26 @@ extension Double {
extension Double {
/// EZSE: Returns a Double rounded to decimal
public func getRoundedByPlaces(places: Int) -> Double {
return castToDecimalByPlacesHelper(places, function: round)
public func getRoundedByPlaces(_ places: Int) -> Double {
return castToDecimalByPlacesHelper(places, function: Darwin.round)
}
/// EZSE: Rounds the current Double rounded to decimal
public mutating func roundByPlaces(places: Int) {
self = castToDecimalByPlacesHelper(places, function: round)
public mutating func roundByPlaces(_ places: Int) {
self = castToDecimalByPlacesHelper(places, function: Darwin.round)
}
/// EZSE: Returns a Double Ceil to decimal
public func getCeiledByPlaces(places: Int) -> Double {
return castToDecimalByPlacesHelper(places, function: ceil)
public func getCeiledByPlaces(_ places: Int) -> Double {
return castToDecimalByPlacesHelper(places, function: Darwin.ceil)
}
/// EZSE: Ceils current Double to number of places
public mutating func ceilByPlaces(places: Int) {
self = castToDecimalByPlacesHelper(places, function: ceil)
public mutating func ceilByPlaces(_ places: Int) {
self = castToDecimalByPlacesHelper(places, function: Darwin.ceil)
}
private func castToDecimalByPlacesHelper(places: Int, function: (Double) -> Double) -> Double {
fileprivate func castToDecimalByPlacesHelper(_ places: Int, function: (Double) -> Double) -> Double {
guard places >= 0 else { return self }
let divisor = pow(10.0, Double(places))
return function(self * divisor) / divisor

View File

@ -12,9 +12,9 @@ import UIKit
public struct ez {
/// EZSE: Returns app's name
public static var appDisplayName: String? {
if let bundleDisplayName = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleDisplayName") as? String {
if let bundleDisplayName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String {
return bundleDisplayName
} else if let bundleName = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleName") as? String {
} else if let bundleName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String {
return bundleName
}
@ -23,17 +23,17 @@ public struct ez {
/// EZSE: Returns app's version number
public static var appVersion: String? {
return NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as? String
return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
}
/// EZSE: Return app's build number
public static var appBuild: String? {
return NSBundle.mainBundle().objectForInfoDictionaryKey(kCFBundleVersionKey as String) as? String
return Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as? String
}
/// EZSE: Return app's bundle ID
public static var appBundleID: String? {
return NSBundle.mainBundle().bundleIdentifier
return Bundle.main.bundleIdentifier
}
/// EZSE: Returns both app's version and build numbers "v0.3(7)"
@ -52,9 +52,9 @@ public struct ez {
public static var deviceVersion: String {
var size: Int = 0
sysctlbyname("hw.machine", nil, &size, nil, 0)
var machine = [CChar](count: Int(size), repeatedValue: 0)
var machine = [CChar](repeating: 0, count: Int(size))
sysctlbyname("hw.machine", &machine, &size, nil, 0)
return String.fromCString(machine)!
return String(cString: machine)
}
/// EZSE: Returns true if DEBUG mode is active //TODO: Add to readme
@ -106,19 +106,19 @@ public struct ez {
/// EZSE: Returns current screen orientation
public static var screenOrientation: UIInterfaceOrientation {
return UIApplication.sharedApplication().statusBarOrientation
return UIApplication.shared.statusBarOrientation
}
#endif
/// EZSwiftExtensions
public static var horizontalSizeClass: UIUserInterfaceSizeClass {
return self.topMostVC?.traitCollection.horizontalSizeClass ?? UIUserInterfaceSizeClass.Unspecified
return self.topMostVC?.traitCollection.horizontalSizeClass ?? UIUserInterfaceSizeClass.unspecified
}
/// EZSwiftExtensions
public static var verticalSizeClass: UIUserInterfaceSizeClass {
return self.topMostVC?.traitCollection.verticalSizeClass ?? UIUserInterfaceSizeClass.Unspecified
return self.topMostVC?.traitCollection.verticalSizeClass ?? UIUserInterfaceSizeClass.unspecified
}
/// EZSE: Returns screen width
@ -127,9 +127,9 @@ public struct ez {
#if os(iOS)
if UIInterfaceOrientationIsPortrait(screenOrientation) {
return UIScreen.mainScreen().bounds.size.width
return UIScreen.main.bounds.size.width
} else {
return UIScreen.mainScreen().bounds.size.height
return UIScreen.main.bounds.size.height
}
#elseif os(tvOS)
@ -145,9 +145,9 @@ public struct ez {
#if os(iOS)
if UIInterfaceOrientationIsPortrait(screenOrientation) {
return UIScreen.mainScreen().bounds.size.height
return UIScreen.main.bounds.size.height
} else {
return UIScreen.mainScreen().bounds.size.width
return UIScreen.main.bounds.size.width
}
#elseif os(tvOS)
@ -161,15 +161,15 @@ public struct ez {
/// EZSE: Returns StatusBar height
public static var screenStatusBarHeight: CGFloat {
return UIApplication.sharedApplication().statusBarFrame.height
return UIApplication.shared.statusBarFrame.height
}
/// EZSE: Return screen's height without StatusBar
public static var screenHeightWithoutStatusBar: CGFloat {
if UIInterfaceOrientationIsPortrait(screenOrientation) {
return UIScreen.mainScreen().bounds.size.height - screenStatusBarHeight
return UIScreen.main.bounds.size.height - screenStatusBarHeight
} else {
return UIScreen.mainScreen().bounds.size.width - screenStatusBarHeight
return UIScreen.main.bounds.size.width - screenStatusBarHeight
}
}
@ -177,104 +177,103 @@ public struct ez {
/// EZSE: Returns the locale country code. An example value might be "ES". //TODO: Add to readme
public static var currentRegion: String? {
return NSLocale.currentLocale().objectForKey(NSLocaleCountryCode) as? String
return (Locale.current as NSLocale).object(forKey: NSLocale.Key.countryCode) as? String
}
/// EZSE: Calls action when a screen shot is taken
public static func detectScreenShot(action: () -> ()) {
let mainQueue = NSOperationQueue.mainQueue()
NSNotificationCenter.defaultCenter().addObserverForName(UIApplicationUserDidTakeScreenshotNotification, object: nil, queue: mainQueue) { notification in
public static func detectScreenShot(_ action: @escaping () -> ()) {
let mainQueue = OperationQueue.main
NotificationCenter.default.addObserver(forName: NSNotification.Name.UIApplicationUserDidTakeScreenshot, object: nil, queue: mainQueue) { notification in
// executes after screenshot
action()
}
}
//TODO: Document this, add tests to this, find a way to remove ++
//TODO: Document this, add tests to this
/// EZSE: Iterates through enum elements, use with (for element in ez.iterateEnum(myEnum))
public static func iterateEnum<T: Hashable>(_: T.Type) -> AnyGenerator<T> {
/// http://stackoverflow.com/questions/24007461/how-to-enumerate-an-enum-with-string-type
public static func iterateEnum<T: Hashable>(_: T.Type) -> AnyIterator<T> {
var i = 0
return AnyGenerator {
let next = withUnsafePointer(&i) { UnsafePointer<T>($0).memory }
return next.hashValue == i++ ? next : nil
return AnyIterator {
let next = withUnsafePointer(to: &i) { $0.withMemoryRebound(to: T.self, capacity: 1) { $0.pointee } }
if next.hashValue != i { return nil }
i += 1
return next
}
}
// MARK: - Dispatch
/// EZSE: Runs the function after x seconds
public static func dispatchDelay(second: Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(second * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
public static func dispatchDelay(_ second: Double, closure:@escaping ()->()) {
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Double(Int64(second * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}
/// EZSE: Runs function after x seconds
public static func runThisAfterDelay(seconds seconds: Double, after: () -> ()) {
runThisAfterDelay(seconds: seconds, queue: dispatch_get_main_queue(), after: after)
public static func runThisAfterDelay(seconds: Double, after: @escaping () -> ()) {
runThisAfterDelay(seconds: seconds, queue: DispatchQueue.main, after: after)
}
//TODO: Make this easier
/// EZSE: Runs function after x seconds with dispatch_queue, use this syntax: dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)
public static func runThisAfterDelay(seconds seconds: Double, queue: dispatch_queue_t, after: ()->()) {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC)))
dispatch_after(time, queue, after)
public static func runThisAfterDelay(seconds: Double, queue: DispatchQueue, after: @escaping ()->()) {
let time = DispatchTime.now() + Double(Int64(seconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
queue.asyncAfter(deadline: time, execute: after)
}
/// EZSE: Submits a block for asynchronous execution on the main queue
public static func runThisInMainThread(block: dispatch_block_t) {
dispatch_async(dispatch_get_main_queue(), block)
public static func runThisInMainThread(_ block: @escaping ()->()) {
DispatchQueue.main.async(execute: block)
}
/// EZSE: Runs in Default priority queue
public static func runThisInBackground(block: () -> ()) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), block)
public static func runThisInBackground(_ block: @escaping () -> ()) {
DispatchQueue.global(qos: .default).async(execute: block)
}
/// EZSE: Runs every second, to cancel use: timer.invalidate()
public static func runThisEvery(seconds seconds: NSTimeInterval, startAfterSeconds: NSTimeInterval, handler: NSTimer! -> Void) -> NSTimer {
public static func runThisEvery(seconds: TimeInterval, startAfterSeconds: TimeInterval, handler: @escaping (CFRunLoopTimer?) -> Void) -> Timer {
let fireDate = startAfterSeconds + CFAbsoluteTimeGetCurrent()
let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, seconds, 0, 0, handler)
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes)
return timer
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, CFRunLoopMode.commonModes)
return timer!
}
/// EZSE: Gobal main queue
public var globalMainQueue: dispatch_queue_t {
return dispatch_get_main_queue()
public var globalMainQueue: DispatchQueue {
return DispatchQueue.main
}
/// EZSE: Gobal queue with user interactive priority
public var globalUserInteractiveQueue: dispatch_queue_t {
return dispatch_get_global_queue(Int(QOS_CLASS_USER_INTERACTIVE.rawValue), 0)
public var globalUserInteractiveQueue: DispatchQueue {
return DispatchQueue.global(qos: .userInteractive)
}
/// EZSE: Gobal queue with user initiated priority
public var globalUserInitiatedQueue: dispatch_queue_t {
return dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.rawValue), 0)
public var globalUserInitiatedQueue: DispatchQueue {
return DispatchQueue.global(qos: .userInitiated)
}
/// EZSE: Gobal queue with utility priority
public var globalUtilityQueue: dispatch_queue_t {
return dispatch_get_global_queue(Int(QOS_CLASS_UTILITY.rawValue), 0)
public var globalUtilityQueue: DispatchQueue {
return DispatchQueue.global(qos: .utility)
}
/// EZSE: Gobal queue with background priority
public var globalBackgroundQueue: dispatch_queue_t {
return dispatch_get_global_queue(Int(QOS_CLASS_BACKGROUND.rawValue), 0)
public var globalBackgroundQueue: DispatchQueue {
return DispatchQueue.global(qos: .background)
}
/// EZSE: Gobal queue with default priority
public var globalQueue: dispatch_queue_t {
return dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
public var globalQueue: DispatchQueue {
return DispatchQueue.global(qos: .default)
}
// MARK: - DownloadTask
/// EZSE: Downloads image from url string
public static func requestImage(url: String, success: (UIImage?) -> Void) {
public static func requestImage(_ url: String, success: @escaping (UIImage?) -> Void) {
requestURL(url, success: { (data) -> Void in
if let d = data {
success(UIImage(data: d))
@ -283,10 +282,10 @@ public struct ez {
}
/// EZSE: Downloads JSON from url string
public static func requestJSON(url: String, success: (AnyObject? -> Void), error: ((NSError) -> Void)?) {
public static func requestJSON(_ url: String, success: @escaping ((Any?) -> Void), error: ((NSError) -> Void)?) {
requestURL(url,
success: { (data) -> Void in
let json: AnyObject? = self.dataToJsonDict(data)
let json = self.dataToJsonDict(data)
success(json)
},
error: { (err) -> Void in
@ -297,14 +296,14 @@ public struct ez {
}
/// EZSE: converts NSData to JSON dictionary
private static func dataToJsonDict(data: NSData?) -> AnyObject? {
fileprivate static func dataToJsonDict(_ data: Data?) -> Any? {
if let d = data {
var error: NSError?
let json: AnyObject?
let json: Any?
do {
json = try NSJSONSerialization.JSONObjectWithData(
d,
options: NSJSONReadingOptions.AllowFragments)
json = try JSONSerialization.jsonObject(
with: d,
options: JSONSerialization.ReadingOptions.allowFragments)
} catch let error1 as NSError {
error = error1
json = nil
@ -321,17 +320,17 @@ public struct ez {
}
/// EZSE:
private static func requestURL(url: String, success: (NSData?) -> Void, error: ((NSError) -> Void)? = nil) {
guard let requestURL = NSURL(string: url) else {
fileprivate static func requestURL(_ url: String, success: @escaping (Data?) -> Void, error: ((NSError) -> Void)? = nil) {
guard let requestURL = URL(string: url) else {
assertionFailure("EZSwiftExtensions Error: Invalid URL")
return
}
NSURLSession.sharedSession().dataTaskWithRequest(
NSURLRequest(URL: requestURL),
URLSession.shared.dataTask(
with: URLRequest(url: requestURL),
completionHandler: { data, response, err in
if let e = err {
error?(e)
error?(e as NSError)
} else {
success(data)
}

View File

@ -7,6 +7,3 @@
//
import UIKit

View File

@ -39,7 +39,7 @@ extension Int {
public var toInt32: Int32 { return Int32(self) }
/// EZSE: Converts integer value to a 0..<Int range. Useful in for loops.
public var range: Range<Int> { return 0..<self }
public var range: CountableRange<Int> { return 0..<self }
/// EZSE: Returns number of digits in the integer.
public var digits: Int {

View File

@ -15,8 +15,8 @@ extension NSAttributedString {
public func bold() -> NSAttributedString {
guard let copy = self.mutableCopy() as? NSMutableAttributedString else { return self }
let range = (self.string as NSString).rangeOfString(self.string)
copy.addAttributes([NSFontAttributeName: UIFont.boldSystemFontOfSize(UIFont.systemFontSize())], range: range)
let range = (self.string as NSString).range(of: self.string)
copy.addAttributes([NSFontAttributeName: UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)], range: range)
return copy
}
@ -26,8 +26,8 @@ extension NSAttributedString {
public func underline() -> NSAttributedString {
guard let copy = self.mutableCopy() as? NSMutableAttributedString else { return self }
let range = (self.string as NSString).rangeOfString(self.string)
copy.addAttributes([NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue], range: range)
let range = (self.string as NSString).range(of: self.string)
copy.addAttributes([NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue], range: range)
return copy
}
@ -37,8 +37,8 @@ extension NSAttributedString {
public func italic() -> NSAttributedString {
guard let copy = self.mutableCopy() as? NSMutableAttributedString else { return self }
let range = (self.string as NSString).rangeOfString(self.string)
copy.addAttributes([NSFontAttributeName: UIFont.italicSystemFontOfSize(UIFont.systemFontSize())], range: range)
let range = (self.string as NSString).range(of: self.string)
copy.addAttributes([NSFontAttributeName: UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)], range: range)
return copy
}
@ -46,9 +46,9 @@ extension NSAttributedString {
public func strikethrough() -> NSAttributedString {
guard let copy = self.mutableCopy() as? NSMutableAttributedString else { return self }
let range = (self.string as NSString).rangeOfString(self.string)
let range = (self.string as NSString).range(of: self.string)
let attributes = [
NSStrikethroughStyleAttributeName: NSNumber(integer: NSUnderlineStyle.StyleSingle.rawValue)]
NSStrikethroughStyleAttributeName: NSNumber(value: NSUnderlineStyle.styleSingle.rawValue as Int)]
copy.addAttributes(attributes, range: range)
return copy
@ -58,18 +58,18 @@ extension NSAttributedString {
#endif
/// EZSE: Adds color attribute to NSAttributedString and returns it
public func color(color: UIColor) -> NSAttributedString {
public func color(_ color: UIColor) -> NSAttributedString {
guard let copy = self.mutableCopy() as? NSMutableAttributedString else { return self }
let range = (self.string as NSString).rangeOfString(self.string)
let range = (self.string as NSString).range(of: self.string)
copy.addAttributes([NSForegroundColorAttributeName: color], range: range)
return copy
}
}
/// EZSE: Appends one NSAttributedString to another NSAttributedString and returns it
public func += (inout left: NSAttributedString, right: NSAttributedString) {
public func += (left: inout NSAttributedString, right: NSAttributedString) {
let ns = NSMutableAttributedString(attributedString: left)
ns.appendAttributedString(right)
ns.append(right)
left = ns
}

View File

@ -8,20 +8,20 @@
import Foundation
public extension NSBundle {
public extension Bundle {
/// EZSE: load xib
// Usage: Set some UIView subclass as xib's owner class
// NSBundle.loadNib("ViewXibName", owner: self) //some UIView subclass
// self.addSubview(self.contentView)
public class func loadNib(name: String, owner: AnyObject!) {
NSBundle.mainBundle().loadNibNamed(name, owner: owner, options: nil)[0]
public class func loadNib(_ name: String, owner: AnyObject!) {
_ = Bundle.main.loadNibNamed(name, owner: owner, options: nil)?[0]
}
/// EZSE: load xib
/// Usage: let view: ViewXibName = NSBundle.loadNib("ViewXibName")
public class func loadNib<T>(name: String) -> T? {
return NSBundle.mainBundle().loadNibNamed(name, owner: nil, options: nil)[0] as? T
public class func loadNib<T>(_ name: String) -> T? {
return Bundle.main.loadNibNamed(name, owner: nil, options: nil)?[0] as? T
}
}

View File

@ -7,31 +7,31 @@
//
import UIKit
extension NSDate {
extension Date {
/// EZSE: Initializes NSDate from string and format
public convenience init?(fromString string: String, format: String) {
let formatter = NSDateFormatter()
public init?(fromString string: String, format: String) {
let formatter = DateFormatter()
formatter.dateFormat = format
if let date = formatter.dateFromString(string) {
self.init(timeInterval: 0, sinceDate: date)
if let date = formatter.date(from: string) {
self = date
} else {
self.init()
self = Date()
return nil
}
}
/// EZSE: Initializes NSDate from string returned from an http response, according to several RFCs
public convenience init? (httpDateString: String) {
if let rfc1123 = NSDate(fromString: httpDateString, format: "EEE',' dd' 'MMM' 'yyyy HH':'mm':'ss zzz") {
self.init(timeInterval: 0, sinceDate: rfc1123)
public init? (httpDateString: String) {
if let rfc1123 = Date(fromString: httpDateString, format: "EEE',' dd' 'MMM' 'yyyy HH':'mm':'ss zzz") {
self = rfc1123
return
}
if let rfc850 = NSDate(fromString: httpDateString, format: "EEEE',' dd'-'MMM'-'yy HH':'mm':'ss z") {
self.init(timeInterval: 0, sinceDate: rfc850)
if let rfc850 = Date(fromString: httpDateString, format: "EEEE',' dd'-'MMM'-'yy HH':'mm':'ss z") {
self = rfc850
return
}
if let asctime = NSDate(fromString: httpDateString, format: "EEE MMM d HH':'mm':'ss yyyy") {
self.init(timeInterval: 0, sinceDate: asctime)
if let asctime = Date(fromString: httpDateString, format: "EEE MMM d HH':'mm':'ss yyyy") {
self = asctime
return
}
//self.init()
@ -39,43 +39,43 @@ extension NSDate {
}
/// EZSE: Converts NSDate to String
public func toString(dateStyle dateStyle: NSDateFormatterStyle = .MediumStyle, timeStyle: NSDateFormatterStyle = .MediumStyle) -> String {
let formatter = NSDateFormatter()
public func toString(dateStyle: DateFormatter.Style = .medium, timeStyle: DateFormatter.Style = .medium) -> String {
let formatter = DateFormatter()
formatter.dateStyle = dateStyle
formatter.timeStyle = timeStyle
return formatter.stringFromDate(self)
return formatter.string(from: self)
}
/// EZSE: Converts NSDate to String, with format
public func toString(format format: String) -> String {
let formatter = NSDateFormatter()
public func toString(format: String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = format
return formatter.stringFromDate(self)
return formatter.string(from: self)
}
/// EZSE: Calculates how many days passed from now to date
public func daysInBetweenDate(date: NSDate) -> Double {
public func daysInBetweenDate(_ date: Date) -> Double {
var diff = self.timeIntervalSinceNow - date.timeIntervalSinceNow
diff = fabs(diff/86400)
return diff
}
/// EZSE: Calculates how many hours passed from now to date
public func hoursInBetweenDate(date: NSDate) -> Double {
public func hoursInBetweenDate(_ date: Date) -> Double {
var diff = self.timeIntervalSinceNow - date.timeIntervalSinceNow
diff = fabs(diff/3600)
return diff
}
/// EZSE: Calculates how many minutes passed from now to date
public func minutesInBetweenDate(date: NSDate) -> Double {
public func minutesInBetweenDate(_ date: Date) -> Double {
var diff = self.timeIntervalSinceNow - date.timeIntervalSinceNow
diff = fabs(diff/60)
return diff
}
/// EZSE: Calculates how many seconds passed from now to date
public func secondsInBetweenDate(date: NSDate) -> Double {
public func secondsInBetweenDate(_ date: Date) -> Double {
var diff = self.timeIntervalSinceNow - date.timeIntervalSinceNow
diff = fabs(diff)
return diff
@ -83,24 +83,24 @@ extension NSDate {
/// EZSE: Easy creation of time passed String. Can be Years, Months, days, hours, minutes or seconds
public func timePassed() -> String {
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: self, toDate: date, options: [])
let date = Date()
let calendar = Calendar.current
let components = (calendar as NSCalendar).components([.year, .month, .day, .hour, .minute, .second], from: self, to: date, options: [])
var str: String
if components.year >= 1 {
if components.year! >= 1 {
components.year == 1 ? (str = "year") : (str = "years")
return "\(components.year) \(str) ago"
} else if components.month >= 1 {
} else if components.month! >= 1 {
components.month == 1 ? (str = "month") : (str = "months")
return "\(components.month) \(str) ago"
} else if components.day >= 1 {
} else if components.day! >= 1 {
components.day == 1 ? (str = "day") : (str = "days")
return "\(components.day) \(str) ago"
} else if components.hour >= 1 {
} else if components.hour! >= 1 {
components.hour == 1 ? (str = "hour") : (str = "hours")
return "\(components.hour) \(str) ago"
} else if components.minute >= 1 {
} else if components.minute! >= 1 {
components.minute == 1 ? (str = "minute") : (str = "minutes")
return "\(components.minute) \(str) ago"
} else if components.second == 0 {
@ -111,17 +111,3 @@ extension NSDate {
}
}
extension NSDate: Comparable {}
/// EZSE: Returns if dates are equal to each other
public func == (lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.isEqualToDate(rhs)
}
/// EZSE: Returns if one date is smaller than the other
public func < (lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.compare(rhs) == .OrderedAscending
}
public func > (lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.compare(rhs) == .OrderedDescending
}

View File

@ -12,7 +12,7 @@ import Foundation
public extension NSDictionary {
/// EZSE: Unserialize JSON string into NSDictionary
public convenience init ? (json: String) {
if let data = (try? NSJSONSerialization.JSONObjectWithData(json.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!, options: NSJSONReadingOptions.MutableContainers)) as? NSDictionary {
if let data = (try? JSONSerialization.jsonObject(with: json.data(using: String.Encoding.utf8, allowLossyConversion: true)!, options: JSONSerialization.ReadingOptions.mutableContainers)) as? NSDictionary {
self.init(dictionary: data)
} else {
self.init()
@ -22,8 +22,8 @@ public extension NSDictionary {
/// EZSE: Serialize NSDictionary into JSON string
public func formatJSON() -> String? {
if let jsonData = try? NSJSONSerialization.dataWithJSONObject(self, options: NSJSONWritingOptions()) {
let jsonStr = NSString(data: jsonData, encoding: NSUTF8StringEncoding)
if let jsonData = try? JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions()) {
let jsonStr = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)
return String(jsonStr ?? "")
}
return nil

View File

@ -9,10 +9,10 @@ import UIKit
extension NSObject {
public var className: String {
return self.dynamicType.className
return type(of: self).className
}
public static var className: String {
return String(self)
return String(describing: self)
}
}

View File

@ -7,24 +7,24 @@
//
import UIKit
extension NSTimer {
extension Timer {
/// EZSE: Runs every x seconds, to cancel use: timer.invalidate()
public static func runThisEvery(seconds seconds: NSTimeInterval, handler: NSTimer! -> Void) -> NSTimer {
public static func runThisEvery(seconds: TimeInterval, handler: @escaping (CFRunLoopTimer?) -> Void) -> Timer {
let fireDate = CFAbsoluteTimeGetCurrent()
let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, seconds, 0, 0, handler)
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes)
return timer
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, CFRunLoopMode.commonModes)
return timer!
}
/// EZSE: Run function after x seconds
public static func runThisAfterDelay(seconds seconds: Double, after: () -> ()) {
runThisAfterDelay(seconds: seconds, queue: dispatch_get_main_queue(), after: after)
public static func runThisAfterDelay(seconds: Double, after: @escaping () -> ()) {
runThisAfterDelay(seconds: seconds, queue: DispatchQueue.main, after: after)
}
//TODO: Make this easier
/// EZSwiftExtensions - dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)
public static func runThisAfterDelay(seconds seconds: Double, queue: dispatch_queue_t, after: ()->()) {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC)))
dispatch_after(time, queue, after)
public static func runThisAfterDelay(seconds: Double, queue: DispatchQueue, after: @escaping ()->()) {
let time = DispatchTime.now() + Double(Int64(seconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
queue.asyncAfter(deadline: time, execute: after)
}
}

View File

@ -11,10 +11,10 @@
import UIKit
extension NSURL {
extension URL {
/// EZSE: Returns convert query to Dictionary
public var queryParameters: [String: String]? {
guard let components = NSURLComponents(URL: self, resolvingAgainstBaseURL: true), queryItems = components.queryItems else {
guard let components = URLComponents(url: self, resolvingAgainstBaseURL: true), let queryItems = components.queryItems else {
return nil
}
@ -27,54 +27,54 @@ extension NSURL {
}
/// EZSE: Returns remote size of url, don't use it in main thread
public func remoteSize(completionHandler: ((contentLength: Int64) -> Void), timeoutInterval: NSTimeInterval = 30) {
let request = NSMutableURLRequest(URL: self, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: timeoutInterval)
request.HTTPMethod = "HEAD"
public func remoteSize(_ completionHandler: @escaping ((_ contentLength: Int64) -> Void), timeoutInterval: TimeInterval = 30) {
let request = NSMutableURLRequest(url: self, cachePolicy: NSURLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: timeoutInterval)
request.httpMethod = "HEAD"
request.setValue("", forHTTPHeaderField: "Accept-Encoding")
NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (_, response, _) -> Void in
URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
let contentLength: Int64 = response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
completionHandler(contentLength: contentLength)
DispatchQueue.global(qos: .default).async(execute: {
completionHandler(contentLength)
})
}).resume()
}.resume()
}
/// EZSE: Returns server supports resuming or not, don't use it in main thread
public func supportsResume(completionHandler: ((doesSupport: Bool) -> Void), timeoutInterval: NSTimeInterval = 30) {
let request = NSMutableURLRequest(URL: self, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: timeoutInterval)
request.HTTPMethod = "HEAD"
public func supportsResume(_ completionHandler: @escaping ((_ doesSupport: Bool) -> Void), timeoutInterval: TimeInterval = 30) {
let request = NSMutableURLRequest(url: self, cachePolicy: NSURLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: timeoutInterval)
request.httpMethod = "HEAD"
request.setValue("bytes=5-10", forHTTPHeaderField: "Range")
NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (_, response, _) -> Void in
let responseCode = (response as? NSHTTPURLResponse)?.statusCode ?? -1
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
completionHandler(doesSupport: responseCode == 206)
URLSession.shared.dataTask(with: request as URLRequest) { (_, response, _) -> Void in
let responseCode = (response as? HTTPURLResponse)?.statusCode ?? -1
DispatchQueue.global(qos: .default).async(execute: {
completionHandler(responseCode == 206)
})
}).resume()
}.resume()
}
/// EZSE: Compare two URLs
public func isSameWithURL(url: NSURL) -> Bool {
public func isSameWithURL(_ url: URL) -> Bool {
if self == url {
return true
}
if self.scheme.lowercaseString != url.scheme.lowercaseString {
if self.scheme?.lowercased() != url.scheme?.lowercased() {
return false
}
if let host1 = self.host, host2 = url.host {
if let host1 = self.host, let host2 = url.host {
let whost1 = host1.hasPrefix("www.") ? host1 : "www." + host1
let whost2 = host2.hasPrefix("www.") ? host2 : "www." + host2
if whost1 != whost2 {
return false
}
}
let pathdelimiter = NSCharacterSet(charactersInString: "/")
if self.path?.lowercaseString.stringByTrimmingCharactersInSet(pathdelimiter) != url.path?.lowercaseString.stringByTrimmingCharactersInSet(pathdelimiter) {
let pathdelimiter = CharacterSet(charactersIn: "/")
if self.path.lowercased().trimmingCharacters(in: pathdelimiter) != url.path.lowercased().trimmingCharacters(in: pathdelimiter) {
return false
}
if self.port != url.port {
if (self as NSURL).port != (url as NSURL).port {
return false
}
if self.query?.lowercaseString != url.query?.lowercaseString {
if self.query?.lowercased() != url.query?.lowercased() {
return false
}
return true
@ -84,43 +84,43 @@ extension NSURL {
public var fileIsDirectory: Bool {
var isdirv: AnyObject?
do {
try self.getResourceValue(&isdirv, forKey: NSURLIsDirectoryKey)
try (self as NSURL).getResourceValue(&isdirv, forKey: URLResourceKey.isDirectoryKey)
} catch _ {
}
return isdirv?.boolValue ?? false
}
/// EZSE: File modification date, nil if file doesn't exist
public var fileModifiedDate: NSDate? {
public var fileModifiedDate: Date? {
get {
var datemodv: AnyObject?
do {
try self.getResourceValue(&datemodv, forKey: NSURLContentModificationDateKey)
try (self as NSURL).getResourceValue(&datemodv, forKey: URLResourceKey.contentModificationDateKey)
} catch _ {
}
return datemodv as? NSDate
return datemodv as? Date
}
set {
do {
try self.setResourceValue(newValue, forKey: NSURLContentModificationDateKey)
try (self as NSURL).setResourceValue(newValue, forKey: URLResourceKey.contentModificationDateKey)
} catch _ {
}
}
}
/// EZSE: File creation date, nil if file doesn't exist
public var fileCreationDate: NSDate? {
public var fileCreationDate: Date? {
get {
var datecreatev: AnyObject?
do {
try self.getResourceValue(&datecreatev, forKey: NSURLCreationDateKey)
try (self as NSURL).getResourceValue(&datecreatev, forKey: URLResourceKey.creationDateKey)
} catch _ {
}
return datecreatev as? NSDate
return datecreatev as? Date
}
set {
do {
try self.setResourceValue(newValue, forKey: NSURLCreationDateKey)
try (self as NSURL).setResourceValue(newValue, forKey: URLResourceKey.creationDateKey)
} catch _ {
}
@ -128,24 +128,24 @@ extension NSURL {
}
/// EZSE: Returns last file access date, nil if file doesn't exist or not yet accessed
public var fileAccessDate: NSDate? {
NSURLCustomIconKey
public var fileAccessDate: Date? {
_ = URLResourceKey.customIconKey
var dateaccessv: AnyObject?
do {
try self.getResourceValue(&dateaccessv, forKey: NSURLContentAccessDateKey)
try (self as NSURL).getResourceValue(&dateaccessv, forKey: URLResourceKey.contentAccessDateKey)
} catch _ {
}
return dateaccessv as? NSDate
return dateaccessv as? Date
}
/// EZSE: Returns file size, -1 if file doesn't exist
public var fileSize: Int64 {
var sizev: AnyObject?
do {
try self.getResourceValue(&sizev, forKey: NSURLFileSizeKey)
try (self as NSURL).getResourceValue(&sizev, forKey: URLResourceKey.fileSizeKey)
} catch _ {
}
return sizev?.longLongValue ?? -1
return sizev?.int64Value ?? -1
}
/// EZSE: File is hidden or not, don't care about files beginning with dot
@ -153,14 +153,14 @@ extension NSURL {
get {
var ishiddenv: AnyObject?
do {
try self.getResourceValue(&ishiddenv, forKey: NSURLIsHiddenKey)
try (self as NSURL).getResourceValue(&ishiddenv, forKey: URLResourceKey.isHiddenKey)
} catch _ {
}
return ishiddenv?.boolValue ?? false
}
set {
do {
try self.setResourceValue(newValue, forKey: NSURLIsHiddenKey)
try (self as NSURL).setResourceValue(newValue, forKey: URLResourceKey.isHiddenKey)
} catch _ {
}
@ -171,7 +171,7 @@ extension NSURL {
public var fileIsWritable: Bool {
var isdirv: AnyObject?
do {
try self.getResourceValue(&isdirv, forKey: NSURLIsWritableKey)
try (self as NSURL).getResourceValue(&isdirv, forKey: URLResourceKey.isWritableKey)
} catch _ {
}
return isdirv?.boolValue ?? false
@ -215,7 +215,7 @@ extension NSURL {
get {
var thumbsData: AnyObject?
do {
try self.getResourceValue(&thumbsData, forKey: NSURLThumbnailDictionaryKey)
try (self as NSURL).getResourceValue(&thumbsData, forKey: URLResourceKey.thumbnailDictionaryKey)
} catch _ {
}
return thumbsData as? [String: UIImage]
@ -223,7 +223,7 @@ extension NSURL {
set {
do {
let dic = NSDictionary(dictionary: newValue ?? [:])
try self.setResourceValue(dic, forKey: NSURLThumbnailDictionaryKey)
try (self as NSURL).setResourceValue(dic, forKey: URLResourceKey.thumbnailDictionaryKey)
} catch _ {
}
}
@ -233,36 +233,36 @@ extension NSURL {
@available(iOS 8.0, *)
var fileThumbnail1024px: UIImage? {
get {
return fileThumbnailsDictionary?[NSThumbnail1024x1024SizeKey]
return fileThumbnailsDictionary?[URLThumbnailDictionaryItem.NSThumbnail1024x1024SizeKey.rawValue]
}
set {
assert(newValue == nil || (newValue?.size.height == 1024 && newValue?.size.width == 1024), "Image size set in fileThumbnail1024px is not 1024x1024")
fileThumbnailsDictionary?[NSThumbnail1024x1024SizeKey] = newValue
fileThumbnailsDictionary?[URLThumbnailDictionaryItem.NSThumbnail1024x1024SizeKey.rawValue] = newValue
}
}
#endif
/// EZSE: Set SkipBackup attrubute of file or directory in iOS. return current state if no value is set
public func skipBackupAttributeToItemAtURL(skip: Bool? = nil) -> Bool {
let keys = [NSURLIsDirectoryKey, NSURLFileSizeKey]
let enumOpt = NSDirectoryEnumerationOptions()
if NSFileManager.defaultManager().fileExistsAtPath(self.path!) {
public func skipBackupAttributeToItemAtURL(_ skip: Bool? = nil) -> Bool {
let keys = [URLResourceKey.isDirectoryKey, URLResourceKey.fileSizeKey]
let enumOpt = FileManager.DirectoryEnumerationOptions()
if FileManager.default.fileExists(atPath: self.path) {
if skip != nil {
if self.fileIsDirectory {
let filesList = (try? NSFileManager.defaultManager().contentsOfDirectoryAtURL(self, includingPropertiesForKeys: keys, options: enumOpt)) ?? []
let filesList = (try? FileManager.default.contentsOfDirectory(at: self, includingPropertiesForKeys: keys, options: enumOpt)) ?? []
for fileURL in filesList {
fileURL.skipBackupAttributeToItemAtURL(skip)
_ = fileURL.skipBackupAttributeToItemAtURL(skip)
}
}
do {
try self.setResourceValue(NSNumber(bool: skip!), forKey: NSURLIsExcludedFromBackupKey)
try (self as NSURL).setResourceValue(NSNumber(value: skip! as Bool), forKey: URLResourceKey.isExcludedFromBackupKey)
return true
} catch _ {
return false
}
} else {
let dict = try? self.resourceValuesForKeys([NSURLIsExcludedFromBackupKey])
if let key: AnyObject = dict?[NSURLIsExcludedFromBackupKey] {
let dict = try? (self as NSURL).resourceValues(forKeys: [URLResourceKey.isExcludedFromBackupKey])
if let key: AnyObject = dict?[URLResourceKey.isExcludedFromBackupKey] as AnyObject? {
return key.boolValue
}
return false

View File

@ -8,13 +8,13 @@
import Foundation
public extension NSUserDefaults {
public extension UserDefaults {
public subscript(key: String) -> AnyObject? {
get {
return objectForKey(key)
return object(forKey: key) as AnyObject?
}
set {
setObject(newValue, forKey: key)
set(newValue, forKey: key)
}
}
}

View File

@ -17,9 +17,9 @@ import UIKit
extension String {
/// EZSE: Init string with a base64 encoded string
init ? (base64: String) {
let pad = String(count: base64.length % 4, repeatedValue: Character("="))
let pad = String(repeating: "=", count: base64.length % 4)
let base64Padded = base64 + pad
if let decodedData = NSData(base64EncodedString: base64Padded, options: NSDataBase64DecodingOptions(rawValue: 0)), decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding) {
if let decodedData = Data(base64Encoded: base64Padded, options: NSData.Base64DecodingOptions(rawValue: 0)), let decodedString = NSString(data: decodedData, encoding: String.Encoding.utf8.rawValue) {
self.init(decodedString)
return
}
@ -28,21 +28,21 @@ extension String {
/// EZSE: base64 encoded of string
var base64: String {
let plainData = (self as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let base64String = plainData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
let plainData = (self as NSString).data(using: String.Encoding.utf8.rawValue)
let base64String = plainData!.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
return base64String
}
/// EZSE: Cut string from integerIndex to the end
public subscript(integerIndex: Int) -> Character {
let index = startIndex.advancedBy(integerIndex)
let index = characters.index(startIndex, offsetBy: integerIndex)
return self[index]
}
/// EZSE: Cut string from range
public subscript(integerRange: Range<Int>) -> String {
let start = startIndex.advancedBy(integerRange.startIndex)
let end = startIndex.advancedBy(integerRange.endIndex)
let start = characters.index(startIndex, offsetBy: integerRange.lowerBound)
let end = characters.index(startIndex, offsetBy: integerRange.upperBound)
let range = start..<end
return self[range]
}
@ -53,14 +53,14 @@ extension String {
}
/// EZSE: Counts number of instances of the input inside String
public func count(substring: String) -> Int {
return componentsSeparatedByString(substring).count - 1
public func count(_ substring: String) -> Int {
return components(separatedBy: substring).count - 1
}
/// EZSE: Capitalizes first character of String
public mutating func capitalizeFirst() {
guard characters.count > 0 else { return }
self.replaceRange(startIndex...startIndex, with: String(self[startIndex]).capitalizedString)
self.replaceSubrange(startIndex...startIndex, with: String(self[startIndex]).capitalized)
}
/// EZSE: Capitalizes first character of String, returns a new string
@ -68,136 +68,136 @@ extension String {
guard characters.count > 0 else { return self }
var result = self
result.replaceRange(startIndex...startIndex, with: String(self[startIndex]).capitalizedString)
result.replaceSubrange(startIndex...startIndex, with: String(self[startIndex]).capitalized)
return result
}
/// EZSE: Uppercases first 'count' characters of String
public mutating func uppercasePrefix(count: Int) {
public mutating func uppercasePrefix(_ count: Int) {
guard characters.count > 0 && count > 0 else { return }
self.replaceRange(startIndex..<startIndex.advancedBy(min(count, length)),
with: String(self[startIndex..<startIndex.advancedBy(min(count, length))]).uppercaseString)
self.replaceSubrange(startIndex..<self.index(startIndex, offsetBy: min(count, length)),
with: String(self[startIndex..<self.index(startIndex, offsetBy: min(count, length))]).uppercased())
}
/// EZSE: Uppercases first 'count' characters of String, returns a new string
public func uppercasedPrefix(count: Int) -> String {
public func uppercasedPrefix(_ count: Int) -> String {
guard characters.count > 0 && count > 0 else { return self }
var result = self
result.replaceRange(startIndex..<startIndex.advancedBy(min(count, length)),
with: String(self[startIndex..<startIndex.advancedBy(min(count, length))]).uppercaseString)
result.replaceSubrange(startIndex..<self.index(startIndex, offsetBy: min(count, length)),
with: String(self[startIndex..<self.index(startIndex, offsetBy: min(count, length))]).uppercased())
return result
}
/// EZSE: Uppercases last 'count' characters of String
public mutating func uppercaseSuffix(count: Int) {
public mutating func uppercaseSuffix(_ count: Int) {
guard characters.count > 0 && count > 0 else { return }
self.replaceRange(endIndex.advancedBy(-min(count, length))..<endIndex,
with: String(self[endIndex.advancedBy(-min(count, length))..<endIndex]).uppercaseString)
self.replaceSubrange(self.index(endIndex, offsetBy: -min(count, length))..<endIndex,
with: String(self[self.index(endIndex, offsetBy: -min(count, length))..<endIndex]).uppercased())
}
/// EZSE: Uppercases last 'count' characters of String, returns a new string
public func uppercasedSuffix(count: Int) -> String {
public func uppercasedSuffix(_ count: Int) -> String {
guard characters.count > 0 && count > 0 else { return self }
var result = self
result.replaceRange(endIndex.advancedBy(-min(count, length))..<endIndex,
with: String(self[endIndex.advancedBy(-min(count, length))..<endIndex]).uppercaseString)
result.replaceSubrange(characters.index(endIndex, offsetBy: -min(count, length))..<endIndex,
with: String(self[characters.index(endIndex, offsetBy: -min(count, length))..<endIndex]).uppercased())
return result
}
/// EZSE: Uppercases string in range 'range' (from range.startIndex to range.endIndex)
public mutating func uppercase(range range: Range<Int>) {
let from = max(range.startIndex, 0), to = min(range.endIndex, length)
public mutating func uppercase(range: CountableRange<Int>) {
let from = max(range.lowerBound, 0), to = min(range.upperBound, length)
guard characters.count > 0 && (0..<length).contains(from) else { return }
self.replaceRange(startIndex.advancedBy(from)..<startIndex.advancedBy(to),
with: String(self[startIndex.advancedBy(from)..<startIndex.advancedBy(to)]).uppercaseString)
self.replaceSubrange(self.index(startIndex, offsetBy: from)..<self.index(startIndex, offsetBy: to),
with: String(self[self.index(startIndex, offsetBy: from)..<self.index(startIndex, offsetBy: to)]).uppercased())
}
/// EZSE: Uppercases string in range 'range' (from range.startIndex to range.endIndex), returns new string
public func uppercased(range range: Range<Int>) -> String {
let from = max(range.startIndex, 0), to = min(range.endIndex, length)
public func uppercased(range: CountableRange<Int>) -> String {
let from = max(range.lowerBound, 0), to = min(range.upperBound, length)
guard characters.count > 0 && (0..<length).contains(from) else { return self }
var result = self
result.replaceRange(startIndex.advancedBy(from)..<startIndex.advancedBy(to),
with: String(self[startIndex.advancedBy(from)..<startIndex.advancedBy(to)]).uppercaseString)
result.replaceSubrange(characters.index(startIndex, offsetBy: from)..<characters.index(startIndex, offsetBy: to),
with: String(self[characters.index(startIndex, offsetBy: from)..<characters.index(startIndex, offsetBy: to)]).uppercased())
return result
}
/// EZSE: Lowercases first character of String
public mutating func lowercaseFirst() {
guard characters.count > 0 else { return }
self.replaceRange(startIndex...startIndex, with: String(self[startIndex]).lowercaseString)
self.replaceSubrange(startIndex...startIndex, with: String(self[startIndex]).lowercased())
}
/// EZSE: Lowercases first character of String, returns a new string
public func lowercasedFirst() -> String {
guard characters.count > 0 else { return self }
var result = self
result.replaceRange(startIndex...startIndex, with: String(self[startIndex]).lowercaseString)
result.replaceSubrange(startIndex...startIndex, with: String(self[startIndex]).lowercased())
return result
}
/// EZSE: Lowercases first 'count' characters of String
public mutating func lowercasePrefix(count: Int) {
public mutating func lowercasePrefix(_ count: Int) {
guard characters.count > 0 && count > 0 else { return }
self.replaceRange(startIndex..<startIndex.advancedBy(min(count, length)),
with: String(self[startIndex..<startIndex.advancedBy(min(count, length))]).lowercaseString)
self.replaceSubrange(startIndex..<self.index(startIndex, offsetBy: min(count, length)),
with: String(self[startIndex..<self.index(startIndex, offsetBy: min(count, length))]).lowercased())
}
/// EZSE: Lowercases first 'count' characters of String, returns a new string
public func lowercasedPrefix(count: Int) -> String {
public func lowercasedPrefix(_ count: Int) -> String {
guard characters.count > 0 && count > 0 else { return self }
var result = self
result.replaceRange(startIndex..<startIndex.advancedBy(min(count, length)),
with: String(self[startIndex..<startIndex.advancedBy(min(count, length))]).lowercaseString)
result.replaceSubrange(startIndex..<characters.index(startIndex, offsetBy: min(count, length)),
with: String(self[startIndex..<characters.index(startIndex, offsetBy: min(count, length))]).lowercased())
return result
}
/// EZSE: Lowercases last 'count' characters of String
public mutating func lowercaseSuffix(count: Int) {
public mutating func lowercaseSuffix(_ count: Int) {
guard characters.count > 0 && count > 0 else { return }
self.replaceRange(endIndex.advancedBy(-min(count, length))..<endIndex,
with: String(self[endIndex.advancedBy(-min(count, length))..<endIndex]).lowercaseString)
self.replaceSubrange(self.index(endIndex, offsetBy: -min(count, length))..<endIndex,
with: String(self[self.index(endIndex, offsetBy: -min(count, length))..<endIndex]).lowercased())
}
/// EZSE: Lowercases last 'count' characters of String, returns a new string
public func lowercasedSuffix(count: Int) -> String {
public func lowercasedSuffix(_ count: Int) -> String {
guard characters.count > 0 && count > 0 else { return self }
var result = self
result.replaceRange(endIndex.advancedBy(-min(count, length))..<endIndex,
with: String(self[endIndex.advancedBy(-min(count, length))..<endIndex]).lowercaseString)
result.replaceSubrange(characters.index(endIndex, offsetBy: -min(count, length))..<endIndex,
with: String(self[characters.index(endIndex, offsetBy: -min(count, length))..<endIndex]).lowercased())
return result
}
/// EZSE: Lowercases string in range 'range' (from range.startIndex to range.endIndex)
public mutating func lowercase(range range: Range<Int>) {
let from = max(range.startIndex, 0), to = min(range.endIndex, length)
public mutating func lowercase(range: CountableRange<Int>) {
let from = max(range.lowerBound, 0), to = min(range.upperBound, length)
guard characters.count > 0 && (0..<length).contains(from) else { return }
self.replaceRange(startIndex.advancedBy(from)..<startIndex.advancedBy(to),
with: String(self[startIndex.advancedBy(from)..<startIndex.advancedBy(to)]).lowercaseString)
self.replaceSubrange(self.index(startIndex, offsetBy: from)..<self.index(startIndex, offsetBy: to),
with: String(self[self.index(startIndex, offsetBy: from)..<self.index(startIndex, offsetBy: to)]).lowercased())
}
/// EZSE: Lowercases string in range 'range' (from range.startIndex to range.endIndex), returns new string
public func lowercased(range range: Range<Int>) -> String {
let from = max(range.startIndex, 0), to = min(range.endIndex, length)
public func lowercased(range: CountableRange<Int>) -> String {
let from = max(range.lowerBound, 0), to = min(range.upperBound, length)
guard characters.count > 0 && (0..<length).contains(from) else { return self }
var result = self
result.replaceRange(startIndex.advancedBy(from)..<startIndex.advancedBy(to),
with: String(self[startIndex.advancedBy(from)..<startIndex.advancedBy(to)]).lowercaseString)
result.replaceSubrange(characters.index(startIndex, offsetBy: from)..<characters.index(startIndex, offsetBy: to),
with: String(self[characters.index(startIndex, offsetBy: from)..<characters.index(startIndex, offsetBy: to)]).lowercased())
return result
}
/// EZSE: Counts whitespace & new lines
@available(*, deprecated=1.6, renamed="isBlank")
@available(*, deprecated: 1.6, renamed: "isBlank")
public func isOnlyEmptySpacesAndNewLineCharacters() -> Bool {
let characterSet = NSCharacterSet.whitespaceAndNewlineCharacterSet()
let newText = self.stringByTrimmingCharactersInSet(characterSet)
let characterSet = CharacterSet.whitespacesAndNewlines
let newText = self.trimmingCharacters(in: characterSet)
return newText.isEmpty
}
/// EZSE: Checks if string is empty or consists only of whitespace and newline characters
public var isBlank: Bool {
get {
let trimmed = stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet())
let trimmed = trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.isEmpty
}
}
@ -209,89 +209,89 @@ extension String {
/// EZSE: Trims white space and new line characters, returns a new string
public func trimmed() -> String {
return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
return self.trimmingCharacters(in: .whitespacesAndNewlines)
}
/// EZSE: Position of begining character of substing
public func positionOfSubstring(subString: String, caseInsensitive: Bool = false, fromEnd: Bool = false) -> Int {
public func positionOfSubstring(_ subString: String, caseInsensitive: Bool = false, fromEnd: Bool = false) -> Int {
if subString.isEmpty {
return -1
}
var searchOption = fromEnd ? NSStringCompareOptions.AnchoredSearch : NSStringCompareOptions.BackwardsSearch
var searchOption = fromEnd ? NSString.CompareOptions.anchored : NSString.CompareOptions.backwards
if caseInsensitive {
searchOption.insert(NSStringCompareOptions.CaseInsensitiveSearch)
searchOption.insert(NSString.CompareOptions.caseInsensitive)
}
if let range = self.rangeOfString(subString, options: searchOption) where !range.isEmpty {
return self.startIndex.distanceTo(range.startIndex)
if let range = self.range(of: subString, options: searchOption), !range.isEmpty {
return self.characters.distance(from: self.startIndex, to: range.lowerBound)
}
return -1
}
/// EZSE: split string using a spearator string, returns an array of string
public func split(separator: String) -> [String] {
return self.componentsSeparatedByString(separator).filter {
public func split(_ separator: String) -> [String] {
return self.components(separatedBy: separator).filter {
!$0.trimmed().isEmpty
}
}
/// EZSE: split string with delimiters, returns an array of string
public func split(characters: NSCharacterSet) -> [String] {
return self.componentsSeparatedByCharactersInSet(characters).filter {
public func split(_ characters: CharacterSet) -> [String] {
return self.components(separatedBy: characters).filter {
!$0.trimmed().isEmpty
}
}
/// EZSE : Returns count of words in string
public var countofWords: Int {
let regex = try? NSRegularExpression(pattern: "\\w+", options: NSRegularExpressionOptions())
return regex?.numberOfMatchesInString(self, options: NSMatchingOptions(), range: NSRange(location: 0, length: self.length)) ?? 0
let regex = try? NSRegularExpression(pattern: "\\w+", options: NSRegularExpression.Options())
return regex?.numberOfMatches(in: self, options: NSRegularExpression.MatchingOptions(), range: NSRange(location: 0, length: self.length)) ?? 0
}
/// EZSE : Returns count of paragraphs in string
public var countofParagraphs: Int {
let regex = try? NSRegularExpression(pattern: "\\n", options: NSRegularExpressionOptions())
let str = self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
return (regex?.numberOfMatchesInString(str, options: NSMatchingOptions(), range: NSRange(location:0, length: str.length)) ?? -1) + 1
let regex = try? NSRegularExpression(pattern: "\\n", options: NSRegularExpression.Options())
let str = self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
return (regex?.numberOfMatches(in: str, options: NSRegularExpression.MatchingOptions(), range: NSRange(location:0, length: str.length)) ?? -1) + 1
}
internal func rangeFromNSRange(nsRange: NSRange) -> Range<String.Index>? {
let from16 = utf16.startIndex.advancedBy(nsRange.location, limit: utf16.endIndex)
let to16 = from16.advancedBy(nsRange.length, limit: utf16.endIndex)
internal func rangeFromNSRange(_ nsRange: NSRange) -> Range<String.Index>? {
let from16 = utf16.startIndex.advanced(by: nsRange.location)
let to16 = from16.advanced(by: nsRange.length)
if let from = String.Index(from16, within: self),
to = String.Index(to16, within: self) {
let to = String.Index(to16, within: self) {
return from ..< to
}
return nil
}
/// EZSE: Find matches of regular expression in string
public func matchesForRegexInText(regex: String!) -> [String] {
public func matchesForRegexInText(_ regex: String!) -> [String] {
let regex = try? NSRegularExpression(pattern: regex, options: [])
let results = regex?.matchesInString(self, options: [], range: NSRange(location: 0, length: self.length)) ?? []
return results.map { self.substringWithRange(self.rangeFromNSRange($0.range)!) }
let results = regex?.matches(in: self, options: [], range: NSRange(location: 0, length: self.length)) ?? []
return results.map { self.substring(with: self.rangeFromNSRange($0.range)!) }
}
/// EZSE: Checks if String contains Email
public var isEmail: Bool {
let dataDetector = try? NSDataDetector(types: NSTextCheckingType.Link.rawValue)
let firstMatch = dataDetector?.firstMatchInString(self, options: NSMatchingOptions.ReportCompletion, range: NSRange(location: 0, length: length))
return (firstMatch?.range.location != NSNotFound && firstMatch?.URL?.scheme == "mailto")
let dataDetector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let firstMatch = dataDetector?.firstMatch(in: self, options: NSRegularExpression.MatchingOptions.reportCompletion, range: NSRange(location: 0, length: length))
return (firstMatch?.range.location != NSNotFound && firstMatch?.url?.scheme == "mailto")
}
/// EZSE: Returns if String is a number
public func isNumber() -> Bool {
if let _ = NSNumberFormatter().numberFromString(self) {
if let _ = NumberFormatter().number(from: self) {
return true
}
return false
}
/// EZSE: Extracts URLS from String
public var extractURLs: [NSURL] {
var urls: [NSURL] = []
public var extractURLs: [URL] {
var urls: [URL] = []
let detector: NSDataDetector?
do {
detector = try NSDataDetector(types: NSTextCheckingType.Link.rawValue)
detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
} catch _ as NSError {
detector = nil
}
@ -299,9 +299,9 @@ extension String {
let text = self
if let detector = detector {
detector.enumerateMatchesInString(text, options: [], range: NSRange(location: 0, length: text.characters.count), usingBlock: {
(result: NSTextCheckingResult?, flags: NSMatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
if let result = result, url = result.URL {
detector.enumerateMatches(in: text, options: [], range: NSRange(location: 0, length: text.characters.count), using: {
(result: NSTextCheckingResult?, flags: NSRegularExpression.MatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
if let result = result, let url = result.url {
urls.append(url)
}
})
@ -310,20 +310,20 @@ extension String {
return urls
}
/// EZSE: Checking if String contains input
public func contains(find: String) -> Bool {
return self.rangeOfString(find) != nil
}
// /// EZSE: Checking if String contains input
// public func contains(_ find: String) -> Bool {
// return self.range(of: find) != nil
// }
/// EZSE: Checking if String contains input with comparing options
public func contains(find: String, compareOption: NSStringCompareOptions) -> Bool {
return self.rangeOfString(find, options: compareOption) != nil
public func contains(_ find: String, compareOption: NSString.CompareOptions) -> Bool {
return self.range(of: find, options: compareOption) != nil
}
/// EZSE: Converts String to Int
public func toInt() -> Int? {
if let num = NSNumberFormatter().numberFromString(self) {
return num.integerValue
if let num = NumberFormatter().number(from: self) {
return num.intValue
} else {
return nil
}
@ -331,7 +331,7 @@ extension String {
/// EZSE: Converts String to Double
public func toDouble() -> Double? {
if let num = NSNumberFormatter().numberFromString(self) {
if let num = NumberFormatter().number(from: self) {
return num.doubleValue
} else {
return nil
@ -340,7 +340,7 @@ extension String {
/// EZSE: Converts String to Float
public func toFloat() -> Float? {
if let num = NSNumberFormatter().numberFromString(self) {
if let num = NumberFormatter().number(from: self) {
return num.floatValue
} else {
return nil
@ -348,17 +348,18 @@ extension String {
}
/// EZSE: Converts String to Bool
/// WARNING: not expected behaviour
public func toBool() -> Bool? {
let trimmed = self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).lowercaseString
if trimmed == "true" || trimmed == "false" {
return (trimmed as NSString).boolValue
let trimmedString = trimmed()
if trimmedString == "true" || trimmedString == "false" {
return (trimmedString as NSString).boolValue
}
return nil
}
///EZSE: Returns the first index of the occurency of the character in String
public func getIndexOf(char: Character) -> Int? {
for (index, c) in characters.enumerate() {
public func getIndexOf(_ char: Character) -> Int? {
for (index, c) in characters.enumerated() {
if c == char {
return index
}
@ -373,7 +374,7 @@ extension String {
///EZSE: Returns bold NSAttributedString
public func bold() -> NSAttributedString {
let boldString = NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: UIFont.boldSystemFontOfSize(UIFont.systemFontSize())])
let boldString = NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)])
return boldString
}
@ -381,7 +382,7 @@ extension String {
///EZSE: Returns underlined NSAttributedString
public func underline() -> NSAttributedString {
let underlineString = NSAttributedString(string: self, attributes: [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue])
let underlineString = NSAttributedString(string: self, attributes: [NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue])
return underlineString
}
@ -389,7 +390,7 @@ extension String {
///EZSE: Returns italic NSAttributedString
public func italic() -> NSAttributedString {
let italicString = NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: UIFont.italicSystemFontOfSize(UIFont.systemFontSize())])
let italicString = NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)])
return italicString
}
@ -398,7 +399,7 @@ extension String {
#if os(iOS)
///EZSE: Returns hight of rendered string
func height(width: CGFloat, font: UIFont, lineBreakMode: NSLineBreakMode?) -> CGFloat {
func height(_ width: CGFloat, font: UIFont, lineBreakMode: NSLineBreakMode?) -> CGFloat {
var attrib: [String: AnyObject] = [NSFontAttributeName: font]
if lineBreakMode != nil {
let paragraphStyle = NSMutableParagraphStyle()
@ -406,23 +407,23 @@ extension String {
attrib.updateValue(paragraphStyle, forKey: NSParagraphStyleAttributeName)
}
let size = CGSize(width: width, height: CGFloat(DBL_MAX))
return ceil((self as NSString).boundingRectWithSize(size, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes:attrib, context: nil).height)
return ceil((self as NSString).boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes:attrib, context: nil).height)
}
#endif
///EZSE: Returns NSAttributedString
public func color(color: UIColor) -> NSAttributedString {
public func color(_ color: UIColor) -> NSAttributedString {
let colorString = NSMutableAttributedString(string: self, attributes: [NSForegroundColorAttributeName: color])
return colorString
}
///EZSE: Returns NSAttributedString
public func colorSubString(subString: String, color: UIColor) -> NSMutableAttributedString {
public func colorSubString(_ subString: String, color: UIColor) -> NSMutableAttributedString {
var start = 0
var ranges: [NSRange] = []
while true {
let range = (self as NSString).rangeOfString(subString, options: NSStringCompareOptions.LiteralSearch, range: NSRange(location: start, length: (self as NSString).length - start))
let range = (self as NSString).range(of: subString, options: NSString.CompareOptions.literal, range: NSRange(location: start, length: (self as NSString).length - start))
if range.location == NSNotFound {
break
} else {
@ -440,7 +441,7 @@ extension String {
/// EZSE: Checks if String contains Emoji
public func includesEmoji() -> Bool {
for i in 0...length {
let c: unichar = (self as NSString).characterAtIndex(i)
let c: unichar = (self as NSString).character(at: i)
if (0xD800 <= c && c <= 0xDBFF) || (0xDC00 <= c && c <= 0xDFFF) {
return true
}
@ -452,7 +453,7 @@ extension String {
/// EZSE: copy string to pasteboard
public func addToPasteboard() {
let pasteboard = UIPasteboard.generalPasteboard()
let pasteboard = UIPasteboard.general
pasteboard.string = self
}
@ -462,34 +463,34 @@ extension String {
extension String {
init(_ value: Float, precision: Int) {
let nFormatter = NSNumberFormatter()
nFormatter.numberStyle = .DecimalStyle
let nFormatter = NumberFormatter()
nFormatter.numberStyle = .decimal
nFormatter.maximumFractionDigits = precision
self = nFormatter.stringFromNumber(value)!
self = nFormatter.string(from: NSNumber(value: value))!
}
init(_ value: Double, precision: Int) {
let nFormatter = NSNumberFormatter()
nFormatter.numberStyle = .DecimalStyle
let nFormatter = NumberFormatter()
nFormatter.numberStyle = .decimal
nFormatter.maximumFractionDigits = precision
self = nFormatter.stringFromNumber(value)!
self = nFormatter.string(from: NSNumber(value: value))!
}
}
/// EZSE: Pattern matching of strings via defined functions
public func ~=<T> (pattern: (T -> Bool), value: T) -> Bool {
public func ~=<T> (pattern: ((T) -> Bool), value: T) -> Bool {
return pattern(value)
}
/// EZSE: Can be used in switch-case
public func hasPrefix(prefix: String) -> (value: String) -> Bool {
public func hasPrefix(_ prefix: String) -> (_ value: String) -> Bool {
return { (value: String) -> Bool in
value.hasPrefix(prefix)
}
}
/// EZSE: Can be used in switch-case
public func hasSuffix(suffix: String) -> (value: String) -> Bool {
public func hasSuffix(_ suffix: String) -> (_ value: String) -> Bool {
return { (value: String) -> Bool in
value.hasSuffix(suffix)
}

View File

@ -10,6 +10,6 @@ import UIKit
extension UIAlertController {
/// EZSE: Easy way to present UIAlertController
func show() {
UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(self, animated: true, completion: nil)
UIApplication.shared.keyWindow?.rootViewController?.present(self, animated: true, completion: nil)
}
}

View File

@ -9,13 +9,13 @@ import UIKit
extension UIApplication {
/// EZSE: Run a block in background after app resigns activity
public func runInBackground(closure: () -> Void, expirationHandler: (() -> Void)? = nil) {
dispatch_async(dispatch_get_main_queue()) {
public func runInBackground(_ closure: @escaping () -> Void, expirationHandler: (() -> Void)? = nil) {
DispatchQueue.main.async {
let taskID: UIBackgroundTaskIdentifier
if let expirationHandler = expirationHandler {
taskID = self.beginBackgroundTaskWithExpirationHandler(expirationHandler)
taskID = self.beginBackgroundTask(expirationHandler: expirationHandler)
} else {
taskID = self.beginBackgroundTaskWithExpirationHandler({ })
taskID = self.beginBackgroundTask(expirationHandler: { })
}
closure()
self.endBackgroundTask(taskID)
@ -23,7 +23,7 @@ extension UIApplication {
}
/// EZSE: Get the top most view controller from the base view controller; default param is UIWindow's rootViewController
public class func topViewController(base: UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController) -> UIViewController? {
public class func topViewController(_ base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
if let nav = base as? UINavigationController {
return topViewController(nav.visibleViewController)
}

View File

@ -14,17 +14,17 @@ extension UIButton {
// swiftlint:disable function_parameter_count
public convenience init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat, target: AnyObject, action: Selector) {
self.init(frame: CGRect(x: x, y: y, width: w, height: h))
addTarget(target, action: action, forControlEvents: UIControlEvents.TouchUpInside)
addTarget(target, action: action, for: UIControlEvents.touchUpInside)
}
// swiftlint:enable function_parameter_count
/// EZSwiftExtensions
public func setBackgroundColor(color: UIColor, forState: UIControlState) {
public func setBackgroundColor(_ color: UIColor, forState: UIControlState) {
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), color.CGColor)
CGContextFillRect(UIGraphicsGetCurrentContext(), CGRect(x: 0, y: 0, width: 1, height: 1))
UIGraphicsGetCurrentContext()?.setFillColor(color.cgColor)
UIGraphicsGetCurrentContext()?.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.setBackgroundImage(colorImage, forState: forState)
self.setBackgroundImage(colorImage, for: forState)
}
}

View File

@ -16,8 +16,8 @@ extension UIColor {
/// EZSE: init method with hex string and alpha(default: 1)
public convenience init?(hexString: String, alpha: CGFloat = 1.0) {
var formatted = hexString.stringByReplacingOccurrencesOfString("0x", withString: "")
formatted = formatted.stringByReplacingOccurrencesOfString("#", withString: "")
var formatted = hexString.replacingOccurrences(of: "0x", with: "")
formatted = formatted.replacingOccurrences(of: "#", with: "")
if let hex = Int(formatted, radix: 16) {
let red = CGFloat(CGFloat((hex & 0xFF0000) >> 16)/255.0)
let green = CGFloat(CGFloat((hex & 0x00FF00) >> 8)/255.0)
@ -61,7 +61,7 @@ extension UIColor {
}
/// EZSE: Returns random UIColor with random alpha(default: false)
public static func randomColor(randomAlpha: Bool = false) -> UIColor {
public static func randomColor(_ randomAlpha: Bool = false) -> UIColor {
let randomRed = CGFloat.random()
let randomGreen = CGFloat.random()
let randomBlue = CGFloat.random()
@ -73,7 +73,7 @@ extension UIColor {
private extension CGFloat {
/// SwiftRandom extension
static func random(lower: CGFloat = 0, _ upper: CGFloat = 1) -> CGFloat {
static func random(_ lower: CGFloat = 0, _ upper: CGFloat = 1) -> CGFloat {
return CGFloat(Float(arc4random()) / Float(UINT32_MAX)) * (upper - lower) + lower
}
}

View File

@ -39,17 +39,17 @@ private let DeviceList = [
extension UIDevice {
/// EZSwiftExtensions
public class func idForVendor() -> String? {
return UIDevice.currentDevice().identifierForVendor?.UUIDString
return UIDevice.current.identifierForVendor?.uuidString
}
/// EZSwiftExtensions - Operating system name
public class func systemName() -> String {
return UIDevice.currentDevice().systemName
return UIDevice.current.systemName
}
/// EZSwiftExtensions - Operating system version
public class func systemVersion() -> String {
return UIDevice.currentDevice().systemVersion
return UIDevice.current.systemVersion
}
/// EZSwiftExtensions - Operating system version
@ -59,12 +59,12 @@ extension UIDevice {
/// EZSwiftExtensions
public class func deviceName() -> String {
return UIDevice.currentDevice().name
return UIDevice.current.name
}
/// EZSwiftExtensions
public class func deviceLanguage() -> String {
return NSBundle.mainBundle().preferredLocalizations[0]
return Bundle.main.preferredLocalizations[0]
}
/// EZSwiftExtensions
@ -74,12 +74,12 @@ extension UIDevice {
/// EZSE: Returns true if the device is iPhone //TODO: Add to readme
public class func isPhone() -> Bool {
return UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Phone
return UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.phone
}
/// EZSE: Returns true if the device is iPad //TODO: Add to readme
public class func isPad() -> Bool {
return UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad
return UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad
}
/// EZSwiftExtensions
@ -94,8 +94,8 @@ extension UIDevice {
for child in mirror.children {
let value = child.value
if let value = value as? Int8 where value != 0 {
identifier.append(UnicodeScalar(UInt8(value)))
if let value = value as? Int8, value != 0 {
identifier.append(String(UnicodeScalar(UInt8(value))))
}
}
@ -107,22 +107,22 @@ extension UIDevice {
// MARK: - Device Version Checks
public enum Versions: Float {
case Five = 5.0
case Six = 6.0
case Seven = 7.0
case Eight = 8.0
case Nine = 9.0
case five = 5.0
case six = 6.0
case seven = 7.0
case eight = 8.0
case nine = 9.0
}
public class func isVersion(version: Versions) -> Bool {
public class func isVersion(_ version: Versions) -> Bool {
return systemFloatVersion() >= version.rawValue && systemFloatVersion() < (version.rawValue + 1.0)
}
public class func isVersionOrLater(version: Versions) -> Bool {
public class func isVersionOrLater(_ version: Versions) -> Bool {
return systemFloatVersion() >= version.rawValue
}
public class func isVersionOrEarlier(version: Versions) -> Bool {
public class func isVersionOrEarlier(_ version: Versions) -> Bool {
return systemFloatVersion() < (version.rawValue + 1.0)
}
@ -133,80 +133,80 @@ extension UIDevice {
// MARK: iOS 5 Checks
public class func IS_OS_5() -> Bool {
return isVersion(.Five)
return isVersion(.five)
}
public class func IS_OS_5_OR_LATER() -> Bool {
return isVersionOrLater(.Five)
return isVersionOrLater(.five)
}
public class func IS_OS_5_OR_EARLIER() -> Bool {
return isVersionOrEarlier(.Five)
return isVersionOrEarlier(.five)
}
// MARK: iOS 6 Checks
public class func IS_OS_6() -> Bool {
return isVersion(.Six)
return isVersion(.six)
}
public class func IS_OS_6_OR_LATER() -> Bool {
return isVersionOrLater(.Six)
return isVersionOrLater(.six)
}
public class func IS_OS_6_OR_EARLIER() -> Bool {
return isVersionOrEarlier(.Six)
return isVersionOrEarlier(.six)
}
// MARK: iOS 7 Checks
public class func IS_OS_7() -> Bool {
return isVersion(.Seven)
return isVersion(.seven)
}
public class func IS_OS_7_OR_LATER() -> Bool {
return isVersionOrLater(.Seven)
return isVersionOrLater(.seven)
}
public class func IS_OS_7_OR_EARLIER() -> Bool {
return isVersionOrEarlier(.Seven)
return isVersionOrEarlier(.seven)
}
// MARK: iOS 8 Checks
public class func IS_OS_8() -> Bool {
return isVersion(.Eight)
return isVersion(.eight)
}
public class func IS_OS_8_OR_LATER() -> Bool {
return isVersionOrLater(.Eight)
return isVersionOrLater(.eight)
}
public class func IS_OS_8_OR_EARLIER() -> Bool {
return isVersionOrEarlier(.Eight)
return isVersionOrEarlier(.eight)
}
// MARK: iOS 9 Checks
public class func IS_OS_9() -> Bool {
return isVersion(.Nine)
return isVersion(.nine)
}
public class func IS_OS_9_OR_LATER() -> Bool {
return isVersionOrLater(.Nine)
return isVersionOrLater(.nine)
}
public class func IS_OS_9_OR_EARLIER() -> Bool {
return isVersionOrEarlier(.Nine)
return isVersionOrEarlier(.nine)
}
/// EZSwiftExtensions
public class func isSystemVersionOver(requiredVersion: String) -> Bool {
switch systemVersion().compare(requiredVersion, options: NSStringCompareOptions.NumericSearch) {
case .OrderedSame, .OrderedDescending:
public class func isSystemVersionOver(_ requiredVersion: String) -> Bool {
switch systemVersion().compare(requiredVersion, options: NSString.CompareOptions.numeric) {
case .orderedSame, .orderedDescending:
//println("iOS >= 8.0")
return true
case .OrderedAscending:
case .orderedAscending:
//println("iOS < 8.0")
return false
}

View File

@ -48,15 +48,15 @@ public enum FontName: String {
extension UIFont {
/// EZSwiftExtensions
public class func PrintFontFamily(font: FontName) {
let arr = UIFont.fontNamesForFamilyName(font.rawValue)
public class func PrintFontFamily(_ font: FontName) {
let arr = UIFont.fontNames(forFamilyName: font.rawValue)
for name in arr {
print(name)
}
}
/// EZSwiftExtensions
public class func Font(name: FontName, type: FontType, size: CGFloat) -> UIFont! {
public class func Font(_ name: FontName, type: FontType, size: CGFloat) -> UIFont! {
//Using type
let fontName = name.rawValue + "-" + type.rawValue
if let font = UIFont(name: fontName, size: size) {
@ -79,22 +79,22 @@ extension UIFont {
}
/// EZSwiftExtensions
public class func HelveticaNeue(type type: FontType, size: CGFloat) -> UIFont {
public class func HelveticaNeue(type: FontType, size: CGFloat) -> UIFont {
return Font(.HelveticaNeue, type: type, size: size)
}
/// EZSwiftExtensions
public class func AvenirNext(type type: FontType, size: CGFloat) -> UIFont {
public class func AvenirNext(type: FontType, size: CGFloat) -> UIFont {
return Font(.AvenirNext, type: type, size: size)
}
/// EZSwiftExtensions
public class func AvenirNextDemiBold(size size: CGFloat) -> UIFont {
public class func AvenirNextDemiBold(size: CGFloat) -> UIFont {
return Font(.AvenirNext, type: .DemiBold, size: size)
}
/// EZSwiftExtensions
public class func AvenirNextRegular(size size: CGFloat) -> UIFont {
public class func AvenirNextRegular(size: CGFloat) -> UIFont {
return Font(.AvenirNext, type: .Regular, size: size)
}
}

View File

@ -10,13 +10,13 @@ import UIKit
extension UIImage {
/// EZSE: Returns compressed image to rate from 0 to 1
public func compressImage(rate rate: CGFloat) -> NSData? {
public func compressImage(rate: CGFloat) -> Data? {
return UIImageJPEGRepresentation(self, rate)
}
/// EZSE: Returns Image size in Bytes
public func getSizeAsBytes() -> Int {
return UIImageJPEGRepresentation(self, 1)?.length ?? 0
return UIImageJPEGRepresentation(self, 1)?.count ?? 0
}
/// EZSE: Returns Image size in Kylobites
@ -26,51 +26,51 @@ extension UIImage {
}
/// EZSE: scales image
public class func scaleTo(image image: UIImage, w: CGFloat, h: CGFloat) -> UIImage {
public class func scaleTo(image: UIImage, w: CGFloat, h: CGFloat) -> UIImage {
let newSize = CGSize(width: w, height: h)
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
image.drawInRect(CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}
/// EZSE Returns resized image with width. Might return low quality
public func resizeWithWidth(width: CGFloat) -> UIImage {
public func resizeWithWidth(_ width: CGFloat) -> UIImage {
let aspectSize = CGSize (width: width, height: aspectHeightForWidth(width))
UIGraphicsBeginImageContext(aspectSize)
self.drawInRect(CGRect(origin: CGPoint.zero, size: aspectSize))
self.draw(in: CGRect(origin: CGPoint.zero, size: aspectSize))
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
return img!
}
/// EZSE Returns resized image with height. Might return low quality
public func resizeWithHeight(height: CGFloat) -> UIImage {
public func resizeWithHeight(_ height: CGFloat) -> UIImage {
let aspectSize = CGSize (width: aspectWidthForHeight(height), height: height)
UIGraphicsBeginImageContext(aspectSize)
self.drawInRect(CGRect(origin: CGPoint.zero, size: aspectSize))
self.draw(in: CGRect(origin: CGPoint.zero, size: aspectSize))
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
return img!
}
/// EZSE:
public func aspectHeightForWidth(width: CGFloat) -> CGFloat {
public func aspectHeightForWidth(_ width: CGFloat) -> CGFloat {
return (width * self.size.height) / self.size.width
}
/// EZSE:
public func aspectWidthForHeight(height: CGFloat) -> CGFloat {
public func aspectWidthForHeight(_ height: CGFloat) -> CGFloat {
return (height * self.size.width) / self.size.height
}
/// EZSE: Returns cropped image from CGRect
public func croppedImage(bound: CGRect) -> UIImage? {
public func croppedImage(_ bound: CGRect) -> UIImage? {
guard self.size.width > bound.origin.x else {
print("EZSE: Your cropping X coordinate is larger than the image width")
return nil
@ -80,26 +80,26 @@ extension UIImage {
return nil
}
let scaledBounds: CGRect = CGRect(x: bound.x * self.scale, y: bound.y * self.scale, width: bound.w * self.scale, height: bound.h * self.scale)
let imageRef = CGImageCreateWithImageInRect(self.CGImage, scaledBounds)
let croppedImage: UIImage = UIImage(CGImage: imageRef!, scale: self.scale, orientation: UIImageOrientation.Up)
let imageRef = self.cgImage?.cropping(to: scaledBounds)
let croppedImage: UIImage = UIImage(cgImage: imageRef!, scale: self.scale, orientation: UIImageOrientation.up)
return croppedImage
}
/// EZSE: Use current image for pattern of color
public func withColor(tintColor: UIColor) -> UIImage {
public func withColor(_ tintColor: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
let context = UIGraphicsGetCurrentContext()
CGContextTranslateCTM(context, 0, self.size.height)
CGContextScaleCTM(context, 1.0, -1.0)
CGContextSetBlendMode(context, CGBlendMode.Normal)
context?.translateBy(x: 0, y: self.size.height)
context?.scaleBy(x: 1.0, y: -1.0)
context?.setBlendMode(CGBlendMode.normal)
let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height) as CGRect
CGContextClipToMask(context, rect, self.CGImage)
context?.clip(to: rect, mask: self.cgImage!)
tintColor.setFill()
CGContextFillRect(context, rect)
context?.fill(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext() as UIImage
let newImage = UIGraphicsGetImageFromCurrentImageContext()! as UIImage
UIGraphicsEndImageContext()
return newImage
@ -107,13 +107,13 @@ extension UIImage {
///EZSE: Returns the image associated with the URL
public convenience init?(urlString: String) {
guard let url = NSURL(string: urlString) else {
self.init(data: NSData())
guard let url = URL(string: urlString) else {
self.init(data: Data())
return
}
guard let data = NSData(contentsOfURL: url) else {
guard let data = try? Data(contentsOf: url) else {
print("EZSE: No image in URL \(urlString)")
self.init(data: NSData())
self.init(data: Data())
return
}
self.init(data: data)
@ -124,6 +124,6 @@ extension UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 1, height: 1), false, 0.0)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
return image!
}
}

View File

@ -40,7 +40,7 @@ extension UIImageView {
}
/// EZSwiftExtensions, scales this ImageView size to fit the given width
public func scaleImageFrameToWidth(width width: CGFloat) {
public func scaleImageFrameToWidth(width: CGFloat) {
guard let image = image else {
print("EZSwiftExtensions Error: The image is not set yet!")
return
@ -52,7 +52,7 @@ extension UIImageView {
}
/// EZSwiftExtensions, scales this ImageView size to fit the given height
public func scaleImageFrameToHeight(height height: CGFloat) {
public func scaleImageFrameToHeight(height: CGFloat) {
guard let image = image else {
print("EZSwiftExtensions Error: The image is not set yet!")
return
@ -70,7 +70,7 @@ extension UIImageView {
}
/// EZSwiftExtensions
public func imageWithUrl(url url: String) {
public func imageWithUrl(url: String) {
ez.requestImage(url, success: { (image) -> Void in
if let img = image {
self.image = img
@ -79,7 +79,7 @@ extension UIImageView {
}
/// EZSwiftExtensions
public func imageWithUrl(url url: String, placeholder: UIImage) {
public func imageWithUrl(url: String, placeholder: UIImage) {
self.image = placeholder
ez.requestImage(url, success: { (image) -> Void in
if let img = image {
@ -89,7 +89,7 @@ extension UIImageView {
}
/// EZSwiftExtensions
public func imageWithUrl(url url: String, placeholderNamed: String) {
public func imageWithUrl(url: String, placeholderNamed: String) {
self.image = UIImage(named: placeholderNamed)
ez.requestImage(url, success: { (image) -> Void in
if let img = image {

View File

@ -18,26 +18,26 @@ extension UILabel {
public convenience init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat, fontSize: CGFloat) {
self.init(frame: CGRect(x: x, y: y, width: w, height: h))
font = UIFont.HelveticaNeue(type: FontType.None, size: fontSize)
backgroundColor = UIColor.clearColor()
backgroundColor = UIColor.clear
clipsToBounds = true
textAlignment = NSTextAlignment.Left
userInteractionEnabled = true
textAlignment = NSTextAlignment.left
isUserInteractionEnabled = true
numberOfLines = 1
}
/// EZSwiftExtensions
public func getEstimatedSize(width: CGFloat = CGFloat.max, height: CGFloat = CGFloat.max) -> CGSize {
public func getEstimatedSize(_ width: CGFloat = CGFloat.greatestFiniteMagnitude, height: CGFloat = CGFloat.greatestFiniteMagnitude) -> CGSize {
return sizeThatFits(CGSize(width: width, height: height))
}
/// EZSwiftExtensions
public func getEstimatedHeight() -> CGFloat {
return sizeThatFits(CGSize(width: w, height: CGFloat.max)).height
return sizeThatFits(CGSize(width: w, height: CGFloat.greatestFiniteMagnitude)).height
}
/// EZSwiftExtensions
public func getEstimatedWidth() -> CGFloat {
return sizeThatFits(CGSize(width: CGFloat.max, height: h)).width
return sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: h)).width
}
/// EZSwiftExtensions
@ -58,9 +58,9 @@ extension UILabel {
}
/// EZSwiftExtensions
public func setText(text: String?, animated: Bool, duration: NSTimeInterval?) {
public func setText(_ text: String?, animated: Bool, duration: TimeInterval?) {
if animated {
UIView.transitionWithView(self, duration: duration ?? 0.3, options: .TransitionCrossDissolve, animations: { () -> Void in
UIView.transition(with: self, duration: duration ?? 0.3, options: .transitionCrossDissolve, animations: { () -> Void in
self.text = text
}, completion: nil)
} else {

View File

@ -12,14 +12,14 @@ import UIKit
extension UISlider {
///EZSE: Slider moving to value with animation duration
public func setValue(value: Float, duration: Double) {
UIView.animateWithDuration(duration, animations: { () -> Void in
public func setValue(_ value: Float, duration: Double) {
UIView.animate(withDuration: duration, animations: { () -> Void in
self.setValue(self.value, animated: true)
}) { (bool) -> Void in
UIView.animateWithDuration(duration, animations: { () -> Void in
}, completion: { (bool) -> Void in
UIView.animate(withDuration: duration, animations: { () -> Void in
self.setValue(value, animated: true)
}, completion: nil)
}
})
}
}

View File

@ -13,8 +13,8 @@ extension UIStoryboard {
/// EZSE: Get the application's main storyboard
/// Usage: let storyboard = UIStoryboard.mainStoryboard
public static var mainStoryboard: UIStoryboard? {
let bundle = NSBundle.mainBundle()
guard let name = bundle.objectForInfoDictionaryKey("UIMainStoryboardFile") as? String else {
let bundle = Bundle.main
guard let name = bundle.object(forInfoDictionaryKey: "UIMainStoryboardFile") as? String else {
return nil
}
return UIStoryboard(name: name, bundle: bundle)
@ -23,9 +23,9 @@ extension UIStoryboard {
/// EZSE: Get view controller from storyboard by its class type
/// Usage: let profileVC = storyboard!.instantiateVC(ProfileViewController) /* profileVC is of type ProfileViewController */
/// Warning: identifier should match storyboard ID in storyboard of identifier class
public func instantiateVC<T>(identifier: T.Type) -> T? {
let storyboardID = String(identifier)
if let vc = instantiateViewControllerWithIdentifier(storyboardID) as? T {
public func instantiateVC<T>(_ identifier: T.Type) -> T? {
let storyboardID = String(describing: identifier)
if let vc = instantiateViewController(withIdentifier: storyboardID) as? T {
return vc
} else {
return nil

View File

@ -14,7 +14,7 @@ extension UISwitch {
/// EZSE: toggles Switch
public func toggle() {
self.setOn(!self.on, animated: true)
self.setOn(!self.isOn, animated: true)
}
}

View File

@ -20,22 +20,22 @@ extension UITextField {
public convenience init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat, fontSize: CGFloat) {
self.init(frame: CGRect(x: x, y: y, width: w, height: h))
font = UIFont.HelveticaNeue(type: FontType.None, size: fontSize)
backgroundColor = UIColor.clearColor()
backgroundColor = UIColor.clear
clipsToBounds = true
textAlignment = NSTextAlignment.Left
userInteractionEnabled = true
textAlignment = NSTextAlignment.left
isUserInteractionEnabled = true
}
/// EZSE: Add left padding to the text in textfield
public func addLeftTextPadding(blankSize: CGFloat) {
public func addLeftTextPadding(_ blankSize: CGFloat) {
let leftView = UIView()
leftView.frame = CGRect(x: 0, y: 0, width: blankSize, height: frame.height)
self.leftView = leftView
self.leftViewMode = UITextFieldViewMode.Always
self.leftViewMode = UITextFieldViewMode.always
}
/// EZSE: Add a image icon on the left side of the textfield
public func addLeftIcon(image: UIImage?, frame: CGRect, imageSize: CGSize) {
public func addLeftIcon(_ image: UIImage?, frame: CGRect, imageSize: CGSize) {
let leftView = UIView()
leftView.frame = frame
let imgView = UIImageView()
@ -43,7 +43,7 @@ extension UITextField {
imgView.image = image
leftView.addSubview(imgView)
self.leftView = leftView
self.leftViewMode = UITextFieldViewMode.Always
self.leftViewMode = UITextFieldViewMode.always
}
}

View File

@ -20,28 +20,28 @@ extension UITextView {
public convenience init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat, fontSize: CGFloat) {
self.init(frame: CGRect(x: x, y: y, width: w, height: h))
font = UIFont.HelveticaNeue(type: FontType.None, size: fontSize)
backgroundColor = UIColor.clearColor()
backgroundColor = UIColor.clear
clipsToBounds = true
textAlignment = NSTextAlignment.Left
userInteractionEnabled = true
textAlignment = NSTextAlignment.left
isUserInteractionEnabled = true
#if os(iOS)
editable = false
isEditable = false
#endif
scrollEnabled = false
isScrollEnabled = false
}
#if os(iOS)
/// EZSE: Automatically adds a toolbar with a done button to the top of the keyboard. Tapping the button will dismiss the keyboard.
public func addDoneButton(barStyle: UIBarStyle = .Default, title: String? = nil) {
public func addDoneButton(_ barStyle: UIBarStyle = .default, title: String? = nil) {
let keyboardToolbar = UIToolbar()
keyboardToolbar.items = [
UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil),
UIBarButtonItem(title: title ?? "Done", style: .Done, target: self, action: #selector(resignFirstResponder))
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
UIBarButtonItem(title: title ?? "Done", style: .done, target: self, action: #selector(resignFirstResponder))
]
keyboardToolbar.barStyle = barStyle

View File

@ -11,97 +11,97 @@ import UIKit
extension UIViewController {
// MARK: - Notifications
//TODO: Document this part
public func addNotificationObserver(name: String, selector: Selector) {
NSNotificationCenter.defaultCenter().addObserver(self, selector: selector, name: name, object: nil)
public func addNotificationObserver(_ name: String, selector: Selector) {
NotificationCenter.default.addObserver(self, selector: selector, name: NSNotification.Name(rawValue: name), object: nil)
}
public func removeNotificationObserver(name: String) {
NSNotificationCenter.defaultCenter().removeObserver(self, name: name, object: nil)
public func removeNotificationObserver(_ name: String) {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: name), object: nil)
}
public func removeNotificationObserver() {
NSNotificationCenter.defaultCenter().removeObserver(self)
NotificationCenter.default.removeObserver(self)
}
#if os(iOS)
public func addKeyboardWillShowNotification() {
self.addNotificationObserver(UIKeyboardWillShowNotification, selector: #selector(UIViewController.keyboardWillShowNotification(_:)))
self.addNotificationObserver(NSNotification.Name.UIKeyboardWillShow.rawValue, selector: #selector(UIViewController.keyboardWillShowNotification(_:)))
}
public func addKeyboardDidShowNotification() {
self.addNotificationObserver(UIKeyboardDidShowNotification, selector: #selector(UIViewController.keyboardDidShowNotification(_:)))
self.addNotificationObserver(NSNotification.Name.UIKeyboardDidShow.rawValue, selector: #selector(UIViewController.keyboardDidShowNotification(_:)))
}
public func addKeyboardWillHideNotification() {
self.addNotificationObserver(UIKeyboardWillHideNotification, selector: #selector(UIViewController.keyboardWillHideNotification(_:)))
self.addNotificationObserver(NSNotification.Name.UIKeyboardWillHide.rawValue, selector: #selector(UIViewController.keyboardWillHideNotification(_:)))
}
public func addKeyboardDidHideNotification() {
self.addNotificationObserver(UIKeyboardDidHideNotification, selector: #selector(UIViewController.keyboardDidHideNotification(_:)))
self.addNotificationObserver(NSNotification.Name.UIKeyboardDidHide.rawValue, selector: #selector(UIViewController.keyboardDidHideNotification(_:)))
}
public func removeKeyboardWillShowNotification() {
self.removeNotificationObserver(UIKeyboardWillShowNotification)
self.removeNotificationObserver(NSNotification.Name.UIKeyboardWillShow.rawValue)
}
public func removeKeyboardDidShowNotification() {
self.removeNotificationObserver(UIKeyboardDidShowNotification)
self.removeNotificationObserver(NSNotification.Name.UIKeyboardDidShow.rawValue)
}
public func removeKeyboardWillHideNotification() {
self.removeNotificationObserver(UIKeyboardWillHideNotification)
self.removeNotificationObserver(NSNotification.Name.UIKeyboardWillHide.rawValue)
}
public func removeKeyboardDidHideNotification() {
self.removeNotificationObserver(UIKeyboardDidHideNotification)
self.removeNotificationObserver(NSNotification.Name.UIKeyboardDidHide.rawValue)
}
public func keyboardDidShowNotification(notification: NSNotification) {
if let nInfo = notification.userInfo, value = nInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue {
public func keyboardDidShowNotification(_ notification: Notification) {
if let nInfo = (notification as NSNotification).userInfo, let value = nInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let frame = value.CGRectValue()
let frame = value.cgRectValue
keyboardDidShowWithFrame(frame)
}
}
public func keyboardWillShowNotification(notification: NSNotification) {
if let nInfo = notification.userInfo, value = nInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue {
public func keyboardWillShowNotification(_ notification: Notification) {
if let nInfo = (notification as NSNotification).userInfo, let value = nInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let frame = value.CGRectValue()
let frame = value.cgRectValue
keyboardWillShowWithFrame(frame)
}
}
public func keyboardWillHideNotification(notification: NSNotification) {
if let nInfo = notification.userInfo, value = nInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue {
public func keyboardWillHideNotification(_ notification: Notification) {
if let nInfo = (notification as NSNotification).userInfo, let value = nInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let frame = value.CGRectValue()
let frame = value.cgRectValue
keyboardWillHideWithFrame(frame)
}
}
public func keyboardDidHideNotification(notification: NSNotification) {
if let nInfo = notification.userInfo, value = nInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue {
public func keyboardDidHideNotification(_ notification: Notification) {
if let nInfo = (notification as NSNotification).userInfo, let value = nInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let frame = value.CGRectValue()
let frame = value.cgRectValue
keyboardDidHideWithFrame(frame)
}
}
public func keyboardWillShowWithFrame(frame: CGRect) {
public func keyboardWillShowWithFrame(_ frame: CGRect) {
}
public func keyboardDidShowWithFrame(frame: CGRect) {
public func keyboardDidShowWithFrame(_ frame: CGRect) {
}
public func keyboardWillHideWithFrame(frame: CGRect) {
public func keyboardWillHideWithFrame(_ frame: CGRect) {
}
public func keyboardDidHideWithFrame(frame: CGRect) {
public func keyboardDidHideWithFrame(_ frame: CGRect) {
}
@ -122,11 +122,11 @@ extension UIViewController {
/// EZSwiftExtensions
public var top: CGFloat {
get {
if let me = self as? UINavigationController, visibleViewController = me.visibleViewController {
if let me = self as? UINavigationController, let visibleViewController = me.visibleViewController {
return visibleViewController.top
}
if let nav = self.navigationController {
if nav.navigationBarHidden {
if nav.isNavigationBarHidden {
return view.top
} else {
return nav.navigationBar.bottom
@ -140,11 +140,11 @@ extension UIViewController {
/// EZSwiftExtensions
public var bottom: CGFloat {
get {
if let me = self as? UINavigationController, visibleViewController = me.visibleViewController {
if let me = self as? UINavigationController, let visibleViewController = me.visibleViewController {
return visibleViewController.bottom
}
if let tab = tabBarController {
if tab.tabBar.hidden {
if tab.tabBar.isHidden {
return view.bottom
} else {
return tab.tabBar.top
@ -158,7 +158,7 @@ extension UIViewController {
/// EZSwiftExtensions
public var tabBarHeight: CGFloat {
get {
if let me = self as? UINavigationController, visibleViewController = me.visibleViewController {
if let me = self as? UINavigationController, let visibleViewController = me.visibleViewController {
return visibleViewController.tabBarHeight
}
if let tab = self.tabBarController {
@ -171,7 +171,7 @@ extension UIViewController {
/// EZSwiftExtensions
public var navigationBarHeight: CGFloat {
get {
if let me = self as? UINavigationController, visibleViewController = me.visibleViewController {
if let me = self as? UINavigationController, let visibleViewController = me.visibleViewController {
return visibleViewController.navigationBarHeight
}
if let nav = self.navigationController {
@ -184,7 +184,7 @@ extension UIViewController {
/// EZSwiftExtensions
public var navigationBarColor: UIColor? {
get {
if let me = self as? UINavigationController, visibleViewController = me.visibleViewController {
if let me = self as? UINavigationController, let visibleViewController = me.visibleViewController {
return visibleViewController.navigationBarColor
}
return navigationController?.navigationBar.tintColor
@ -210,46 +210,46 @@ extension UIViewController {
// MARK: - VC Flow
/// EZSwiftExtensions
public func pushVC(vc: UIViewController) {
public func pushVC(_ vc: UIViewController) {
navigationController?.pushViewController(vc, animated: true)
}
/// EZSwiftExtensions
public func popVC() {
navigationController?.popViewControllerAnimated(true)
_ = navigationController?.popViewController(animated: true)
}
/// EZSwiftExtensions
public func presentVC(vc: UIViewController) {
presentViewController(vc, animated: true, completion: nil)
public func presentVC(_ vc: UIViewController) {
present(vc, animated: true, completion: nil)
}
/// EZSwiftExtensions
public func dismissVC(completion completion: (() -> Void)? ) {
dismissViewControllerAnimated(true, completion: completion)
public func dismissVC(completion: (() -> Void)? ) {
dismiss(animated: true, completion: completion)
}
/// EZSwiftExtensions
public func addAsChildViewController(vc: UIViewController, toView: UIView) {
public func addAsChildViewController(_ vc: UIViewController, toView: UIView) {
self.addChildViewController(vc)
toView.addSubview(vc.view)
vc.didMoveToParentViewController(self)
vc.didMove(toParentViewController: self)
}
///EZSE: Adds image named: as a UIImageView in the Background
func setBackgroundImage(named: String) {
func setBackgroundImage(_ named: String) {
let image = UIImage(named: named)
let imageView = UIImageView(frame: view.frame)
imageView.image = image
view.addSubview(imageView)
view.sendSubviewToBack(imageView)
view.sendSubview(toBack: imageView)
}
///EZSE: Adds UIImage as a UIImageView in the Background
@nonobjc func setBackgroundImage(image: UIImage) {
@nonobjc func setBackgroundImage(_ image: UIImage) {
let imageView = UIImageView(frame: view.frame)
imageView.image = image
view.addSubview(imageView)
view.sendSubviewToBack(imageView)
view.sendSubview(toBack: imageView)
}
}

View File

@ -30,7 +30,7 @@ extension UIView {
extension UIView {
/// EZSwiftExtensions, add multiple subviews
public func addSubviews(views: [UIView]) {
public func addSubviews(_ views: [UIView]) {
views.forEach { eachView in
self.addSubview(eachView)
}
@ -52,7 +52,7 @@ extension UIView {
}
/// EZSwiftExtensions, resizes this view so it fits the largest subview
public func resizeToFitSubviews(tagsToIgnore: [Int]) {
public func resizeToFitSubviews(_ tagsToIgnore: [Int]) {
var width: CGFloat = 0
var height: CGFloat = 0
for someView in self.subviews {
@ -190,36 +190,36 @@ extension UIView {
}
/// EZSwiftExtensions
public func leftOffset(offset: CGFloat) -> CGFloat {
public func leftOffset(_ offset: CGFloat) -> CGFloat {
return self.left - offset
}
/// EZSwiftExtensions
public func rightOffset(offset: CGFloat) -> CGFloat {
public func rightOffset(_ offset: CGFloat) -> CGFloat {
return self.right + offset
}
/// EZSwiftExtensions
public func topOffset(offset: CGFloat) -> CGFloat {
public func topOffset(_ offset: CGFloat) -> CGFloat {
return self.top - offset
}
/// EZSwiftExtensions
public func bottomOffset(offset: CGFloat) -> CGFloat {
public func bottomOffset(_ offset: CGFloat) -> CGFloat {
return self.bottom + offset
}
//TODO: Add to readme
/// EZSwiftExtensions
public func alignRight(offset: CGFloat) -> CGFloat {
public func alignRight(_ offset: CGFloat) -> CGFloat {
return self.w - offset
}
/// EZSwiftExtensions
public func reorderSubViews(reorder: Bool = false, tagsToIgnore: [Int] = []) -> CGFloat {
public func reorderSubViews(_ reorder: Bool = false, tagsToIgnore: [Int] = []) -> CGFloat {
var currentHeight: CGFloat = 0
for someView in subviews {
if !tagsToIgnore.contains(someView.tag) && !(someView ).hidden {
if !tagsToIgnore.contains(someView.tag) && !(someView ).isHidden {
if reorder {
let aView = someView
aView.frame = CGRect(x: aView.frame.origin.x, y: currentHeight, width: aView.frame.width, height: aView.frame.height)
@ -266,7 +266,7 @@ extension UIView {
// MARK: Transform Extensions
extension UIView {
/// EZSwiftExtensions
public func setRotationX(x: CGFloat) {
public func setRotationX(_ x: CGFloat) {
var transform = CATransform3DIdentity
transform.m34 = 1.0 / -1000.0
transform = CATransform3DRotate(transform, x.degreesToRadians(), 1.0, 0.0, 0.0)
@ -274,7 +274,7 @@ extension UIView {
}
/// EZSwiftExtensions
public func setRotationY(y: CGFloat) {
public func setRotationY(_ y: CGFloat) {
var transform = CATransform3DIdentity
transform.m34 = 1.0 / -1000.0
transform = CATransform3DRotate(transform, y.degreesToRadians(), 0.0, 1.0, 0.0)
@ -282,7 +282,7 @@ extension UIView {
}
/// EZSwiftExtensions
public func setRotationZ(z: CGFloat) {
public func setRotationZ(_ z: CGFloat) {
var transform = CATransform3DIdentity
transform.m34 = 1.0 / -1000.0
transform = CATransform3DRotate(transform, z.degreesToRadians(), 0.0, 0.0, 1.0)
@ -290,7 +290,7 @@ extension UIView {
}
/// EZSwiftExtensions
public func setRotation(x x: CGFloat, y: CGFloat, z: CGFloat) {
public func setRotation(x: CGFloat, y: CGFloat, z: CGFloat) {
var transform = CATransform3DIdentity
transform.m34 = 1.0 / -1000.0
transform = CATransform3DRotate(transform, x.degreesToRadians(), 1.0, 0.0, 0.0)
@ -300,7 +300,7 @@ extension UIView {
}
/// EZSwiftExtensions
public func setScale(x x: CGFloat, y: CGFloat) {
public func setScale(x: CGFloat, y: CGFloat) {
var transform = CATransform3DIdentity
transform.m34 = 1.0 / -1000.0
transform = CATransform3DScale(transform, x, y, 1)
@ -312,87 +312,87 @@ extension UIView {
// MARK: Layer Extensions
extension UIView {
/// EZSwiftExtensions
public func setCornerRadius(radius radius: CGFloat) {
public func setCornerRadius(radius: CGFloat) {
self.layer.cornerRadius = radius
self.layer.masksToBounds = true
}
//TODO: add this to readme
/// EZSwiftExtensions
public func addShadow(offset offset: CGSize, radius: CGFloat, color: UIColor, opacity: Float, cornerRadius: CGFloat? = nil) {
public func addShadow(offset: CGSize, radius: CGFloat, color: UIColor, opacity: Float, cornerRadius: CGFloat? = nil) {
self.layer.shadowOffset = offset
self.layer.shadowRadius = radius
self.layer.shadowOpacity = opacity
self.layer.shadowColor = color.CGColor
self.layer.shadowColor = color.cgColor
if let r = cornerRadius {
self.layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: r).CGPath
self.layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: r).cgPath
}
}
/// EZSwiftExtensions
public func addBorder(width width: CGFloat, color: UIColor) {
public func addBorder(width: CGFloat, color: UIColor) {
layer.borderWidth = width
layer.borderColor = color.CGColor
layer.borderColor = color.cgColor
layer.masksToBounds = true
}
/// EZSwiftExtensions
public func addBorderTop(size size: CGFloat, color: UIColor) {
public func addBorderTop(size: CGFloat, color: UIColor) {
addBorderUtility(x: 0, y: 0, width: frame.width, height: size, color: color)
}
//TODO: add to readme
/// EZSwiftExtensions
public func addBorderTopWithPadding(size size: CGFloat, color: UIColor, padding: CGFloat) {
public func addBorderTopWithPadding(size: CGFloat, color: UIColor, padding: CGFloat) {
addBorderUtility(x: padding, y: 0, width: frame.width - padding*2, height: size, color: color)
}
/// EZSwiftExtensions
public func addBorderBottom(size size: CGFloat, color: UIColor) {
public func addBorderBottom(size: CGFloat, color: UIColor) {
addBorderUtility(x: 0, y: frame.height - size, width: frame.width, height: size, color: color)
}
/// EZSwiftExtensions
public func addBorderLeft(size size: CGFloat, color: UIColor) {
public func addBorderLeft(size: CGFloat, color: UIColor) {
addBorderUtility(x: 0, y: 0, width: size, height: frame.height, color: color)
}
/// EZSwiftExtensions
public func addBorderRight(size size: CGFloat, color: UIColor) {
public func addBorderRight(size: CGFloat, color: UIColor) {
addBorderUtility(x: frame.width - size, y: 0, width: size, height: frame.height, color: color)
}
/// EZSwiftExtensions
private func addBorderUtility(x x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, color: UIColor) {
fileprivate func addBorderUtility(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, color: UIColor) {
let border = CALayer()
border.backgroundColor = color.CGColor
border.backgroundColor = color.cgColor
border.frame = CGRect(x: x, y: y, width: width, height: height)
layer.addSublayer(border)
}
//TODO: add this to readme
/// EZSwiftExtensions
public func drawCircle(fillColor fillColor: UIColor, strokeColor: UIColor, strokeWidth: CGFloat) {
public func drawCircle(fillColor: UIColor, strokeColor: UIColor, strokeWidth: CGFloat) {
let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.w, height: self.w), cornerRadius: self.w/2)
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.CGPath
shapeLayer.fillColor = fillColor.CGColor
shapeLayer.strokeColor = strokeColor.CGColor
shapeLayer.path = path.cgPath
shapeLayer.fillColor = fillColor.cgColor
shapeLayer.strokeColor = strokeColor.cgColor
shapeLayer.lineWidth = strokeWidth
self.layer.addSublayer(shapeLayer)
}
//TODO: add this to readme
/// EZSwiftExtensions
public func drawStroke(width width: CGFloat, color: UIColor) {
public func drawStroke(width: CGFloat, color: UIColor) {
let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.w, height: self.w), cornerRadius: self.w/2)
let shapeLayer = CAShapeLayer ()
shapeLayer.path = path.CGPath
shapeLayer.fillColor = UIColor.clearColor().CGColor
shapeLayer.strokeColor = color.CGColor
shapeLayer.path = path.cgPath
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = color.cgColor
shapeLayer.lineWidth = width
self.layer.addSublayer(shapeLayer)
}
}
private let UIViewAnimationDuration: NSTimeInterval = 1
private let UIViewAnimationDuration: TimeInterval = 1
private let UIViewAnimationSpringDamping: CGFloat = 0.5
private let UIViewAnimationSpringVelocity: CGFloat = 0.5
@ -400,30 +400,30 @@ private let UIViewAnimationSpringVelocity: CGFloat = 0.5
// MARK: Animation Extensions
extension UIView {
/// EZSwiftExtensions
public func spring(animations animations: (() -> Void), completion: ((Bool) -> Void)? = nil) {
public func spring(animations: @escaping (() -> Void), completion: ((Bool) -> Void)? = nil) {
spring(duration: UIViewAnimationDuration, animations: animations, completion: completion)
}
/// EZSwiftExtensions
public func spring(duration duration: NSTimeInterval, animations: (() -> Void), completion: ((Bool) -> Void)? = nil) {
UIView.animateWithDuration(
UIViewAnimationDuration,
public func spring(duration: TimeInterval, animations: @escaping (() -> Void), completion: ((Bool) -> Void)? = nil) {
UIView.animate(
withDuration: UIViewAnimationDuration,
delay: 0,
usingSpringWithDamping: UIViewAnimationSpringDamping,
initialSpringVelocity: UIViewAnimationSpringVelocity,
options: UIViewAnimationOptions.AllowAnimatedContent,
options: UIViewAnimationOptions.allowAnimatedContent,
animations: animations,
completion: completion
)
}
/// EZSwiftExtensions
public func animate(duration duration: NSTimeInterval, animations: (() -> Void), completion: ((Bool) -> Void)? = nil) {
UIView.animateWithDuration(duration, animations: animations, completion: completion)
public func animate(duration: TimeInterval, animations: @escaping (() -> Void), completion: ((Bool) -> Void)? = nil) {
UIView.animate(withDuration: duration, animations: animations, completion: completion)
}
/// EZSwiftExtensions
public func animate(animations animations: (() -> Void), completion: ((Bool) -> Void)? = nil) {
public func animate(animations: @escaping (() -> Void), completion: ((Bool) -> Void)? = nil) {
animate(duration: UIViewAnimationDuration, animations: animations, completion: completion)
}
@ -446,7 +446,7 @@ extension UIView {
//EZSE: Reverse pop, good for button animations
public func reversePop() {
setScale(x: 0.9, y: 0.9)
UIView.animateWithDuration(0.05, delay: 0, options: UIViewAnimationOptions.AllowUserInteraction, animations: { [weak self] Void in
UIView.animate(withDuration: 0.05, delay: 0, options: UIViewAnimationOptions.allowUserInteraction, animations: { [weak self] Void in
self?.setScale(x: 1, y: 1)
}) { (bool) in }
}
@ -457,11 +457,11 @@ extension UIView {
extension UIView {
/// EZSwiftExtensions
public func toImage () -> UIImage {
UIGraphicsBeginImageContextWithOptions(bounds.size, opaque, 0.0)
drawViewHierarchyInRect(bounds, afterScreenUpdates: false)
UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0.0)
drawHierarchy(in: bounds, afterScreenUpdates: false)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
return img!
}
}
@ -469,22 +469,22 @@ extension UIView {
extension UIView {
/// http://stackoverflow.com/questions/4660371/how-to-add-a-touch-event-to-a-uiview/32182866#32182866
/// EZSwiftExtensions
public func addTapGesture(tapNumber tapNumber: Int = 1, target: AnyObject, action: Selector) {
public func addTapGesture(tapNumber: Int = 1, target: AnyObject, action: Selector) {
let tap = UITapGestureRecognizer(target: target, action: action)
tap.numberOfTapsRequired = tapNumber
addGestureRecognizer(tap)
userInteractionEnabled = true
isUserInteractionEnabled = true
}
/// EZSwiftExtensions - Make sure you use "[weak self] (gesture) in" if you are using the keyword self inside the closure or there might be a memory leak
public func addTapGesture(tapNumber tapNumber: Int = 1, action: ((UITapGestureRecognizer) -> ())?) {
public func addTapGesture(tapNumber: Int = 1, action: ((UITapGestureRecognizer) -> ())?) {
let tap = BlockTap(tapCount: tapNumber, fingerCount: 1, action: action)
addGestureRecognizer(tap)
userInteractionEnabled = true
isUserInteractionEnabled = true
}
/// EZSwiftExtensions
public func addSwipeGesture(direction direction: UISwipeGestureRecognizerDirection, numberOfTouches: Int = 1, target: AnyObject, action: Selector) {
public func addSwipeGesture(direction: UISwipeGestureRecognizerDirection, numberOfTouches: Int = 1, target: AnyObject, action: Selector) {
let swipe = UISwipeGestureRecognizer(target: target, action: action)
swipe.direction = direction
@ -495,37 +495,37 @@ extension UIView {
#endif
addGestureRecognizer(swipe)
userInteractionEnabled = true
isUserInteractionEnabled = true
}
/// EZSwiftExtensions - Make sure you use "[weak self] (gesture) in" if you are using the keyword self inside the closure or there might be a memory leak
public func addSwipeGesture(direction direction: UISwipeGestureRecognizerDirection, numberOfTouches: Int = 1, action: ((UISwipeGestureRecognizer) -> ())?) {
public func addSwipeGesture(direction: UISwipeGestureRecognizerDirection, numberOfTouches: Int = 1, action: ((UISwipeGestureRecognizer) -> ())?) {
let swipe = BlockSwipe(direction: direction, fingerCount: numberOfTouches, action: action)
addGestureRecognizer(swipe)
userInteractionEnabled = true
isUserInteractionEnabled = true
}
/// EZSwiftExtensions
public func addPanGesture(target target: AnyObject, action: Selector) {
public func addPanGesture(target: AnyObject, action: Selector) {
let pan = UIPanGestureRecognizer(target: target, action: action)
addGestureRecognizer(pan)
userInteractionEnabled = true
isUserInteractionEnabled = true
}
/// EZSwiftExtensions - Make sure you use "[weak self] (gesture) in" if you are using the keyword self inside the closure or there might be a memory leak
public func addPanGesture(action action: ((UIPanGestureRecognizer) -> ())?) {
public func addPanGesture(action: ((UIPanGestureRecognizer) -> ())?) {
let pan = BlockPan(action: action)
addGestureRecognizer(pan)
userInteractionEnabled = true
isUserInteractionEnabled = true
}
#if os(iOS)
/// EZSwiftExtensions
public func addPinchGesture(target target: AnyObject, action: Selector) {
public func addPinchGesture(target: AnyObject, action: Selector) {
let pinch = UIPinchGestureRecognizer(target: target, action: action)
addGestureRecognizer(pinch)
userInteractionEnabled = true
isUserInteractionEnabled = true
}
#endif
@ -533,36 +533,36 @@ extension UIView {
#if os(iOS)
/// EZSwiftExtensions - Make sure you use "[weak self] (gesture) in" if you are using the keyword self inside the closure or there might be a memory leak
public func addPinchGesture(action action: ((UIPinchGestureRecognizer) -> ())?) {
public func addPinchGesture(action: ((UIPinchGestureRecognizer) -> ())?) {
let pinch = BlockPinch(action: action)
addGestureRecognizer(pinch)
userInteractionEnabled = true
isUserInteractionEnabled = true
}
#endif
/// EZSwiftExtensions
public func addLongPressGesture(target target: AnyObject, action: Selector) {
public func addLongPressGesture(target: AnyObject, action: Selector) {
let longPress = UILongPressGestureRecognizer(target: target, action: action)
addGestureRecognizer(longPress)
userInteractionEnabled = true
isUserInteractionEnabled = true
}
/// EZSwiftExtensions - Make sure you use "[weak self] (gesture) in" if you are using the keyword self inside the closure or there might be a memory leak
public func addLongPressGesture(action action: ((UILongPressGestureRecognizer) -> ())?) {
public func addLongPressGesture(action: ((UILongPressGestureRecognizer) -> ())?) {
let longPress = BlockLongPress(action: action)
addGestureRecognizer(longPress)
userInteractionEnabled = true
isUserInteractionEnabled = true
}
}
//TODO: add to readme
extension UIView {
/// EZSwiftExtensions [UIRectCorner.TopLeft, UIRectCorner.TopRight]
public func roundCorners(corners: UIRectCorner, radius: CGFloat) {
public func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.CGPath
mask.path = path.cgPath
self.layer.mask = mask
}
@ -574,17 +574,17 @@ extension UIView {
extension UIView {
///EZSE: Shakes the view for as many number of times as given in the argument.
public func shakeViewForTimes(times: Int) {
public func shakeViewForTimes(_ times: Int) {
let anim = CAKeyframeAnimation(keyPath: "transform")
anim.values = [
NSValue(CATransform3D: CATransform3DMakeTranslation(-5, 0, 0 )),
NSValue(CATransform3D: CATransform3DMakeTranslation( 5, 0, 0 ))
NSValue(caTransform3D: CATransform3DMakeTranslation(-5, 0, 0 )),
NSValue(caTransform3D: CATransform3DMakeTranslation( 5, 0, 0 ))
]
anim.autoreverses = true
anim.repeatCount = Float(times)
anim.duration = 7/100
self.layer.addAnimation(anim, forKey: nil)
self.layer.add(anim, forKey: nil)
}
}

View File

@ -11,7 +11,7 @@ import UIKit
extension UIWindow {
/// EZSE: Creates and shows UIWindow. The size will show iPhone4 size until you add launch images with proper sizes. TODO: Add to readme
public convenience init(viewController: UIViewController, backgroundColor: UIColor) {
self.init(frame: UIScreen.mainScreen().bounds)
self.init(frame: UIScreen.main.bounds)
self.rootViewController = viewController
self.backgroundColor = backgroundColor
self.makeKeyAndVisible()