From 30850ccd6410c6733cbc5011c28569662029e990 Mon Sep 17 00:00:00 2001 From: pNre Date: Tue, 9 Jun 2015 21:22:54 +0200 Subject: [PATCH 01/11] First "Swift 2.0" compatibile version --- ExSwift.xcodeproj/project.pbxproj | 12 +- .../xcschemes/ExSwift-Mac.xcscheme | 5 +- .../xcschemes/ExSwift-iOS.xcscheme | 5 +- ExSwift/Array.swift | 356 ++++++++---------- ExSwift/Character.swift | 2 +- ExSwift/Dictionary.swift | 88 ++--- ExSwift/Double.swift | 18 +- ExSwift/ExSwift.swift | 64 ++-- ExSwift/Float.swift | 22 +- ExSwift/Info.plist | 2 +- ExSwift/Int.swift | 66 ++-- ExSwift/NSArray.swift | 6 +- ExSwift/NSDate.swift | 125 +++--- ExSwift/Range.swift | 18 +- ExSwift/Sequence.swift | 98 ++--- ExSwift/String.swift | 181 +++++---- ExSwiftTests/ArrayExtensionsTests.swift | 66 ++-- ExSwiftTests/ExSwiftTests.swift | 12 +- ExSwiftTests/Info.plist | 2 +- ExSwiftTests/IntExtensionsTests.swift | 2 +- ExSwiftTests/NSDateExtensionsTests.swift | 16 +- ExSwiftTests/SequenceExtensionsTests.swift | 62 +-- ExSwiftTests/StringExtensionsTests.swift | 44 +-- Podfile | 4 +- Podfile.lock | 26 +- 25 files changed, 658 insertions(+), 644 deletions(-) diff --git a/ExSwift.xcodeproj/project.pbxproj b/ExSwift.xcodeproj/project.pbxproj index a27961b..14fc70a 100755 --- a/ExSwift.xcodeproj/project.pbxproj +++ b/ExSwift.xcodeproj/project.pbxproj @@ -404,7 +404,8 @@ 1E11AF7B1943222D006BCE48 /* Project object */ = { isa = PBXProject; attributes = { - LastUpgradeCheck = 0600; + LastSwiftUpdateCheck = 0700; + LastUpgradeCheck = 0700; ORGANIZATIONNAME = pNre; TargetAttributes = { 1E11AF831943222D006BCE48 = { @@ -706,6 +707,7 @@ CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_OPTIMIZATION_LEVEL = 0; @@ -788,6 +790,7 @@ INFOPLIST_FILE = ExSwift/Info.plist; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = "co.pNre.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = ExSwift; SKIP_INSTALL = YES; SUPPORTED_PLATFORMS = macosx; @@ -808,6 +811,7 @@ INFOPLIST_FILE = ExSwift/Info.plist; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = "co.pNre.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = ExSwift; SKIP_INSTALL = YES; SUPPORTED_PLATFORMS = macosx; @@ -831,6 +835,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks @executable_path/Frameworks @loader_path/Frameworks"; MACOSX_DEPLOYMENT_TARGET = 10.10; METAL_ENABLE_DEBUG_INFO = YES; + PRODUCT_BUNDLE_IDENTIFIER = "co.pNre.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = ExSwiftTests; SUPPORTED_PLATFORMS = macosx; }; @@ -849,6 +854,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks @executable_path/Frameworks @loader_path/Frameworks"; MACOSX_DEPLOYMENT_TARGET = 10.10; METAL_ENABLE_DEBUG_INFO = NO; + PRODUCT_BUNDLE_IDENTIFIER = "co.pNre.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = ExSwiftTests; SUPPORTED_PLATFORMS = macosx; }; @@ -871,6 +877,7 @@ INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_BUNDLE_IDENTIFIER = "co.pNre.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = ExSwift; SDKROOT = iphoneos; SKIP_INSTALL = YES; @@ -893,6 +900,7 @@ INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_BUNDLE_IDENTIFIER = "co.pNre.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = ExSwift; SDKROOT = iphoneos; SKIP_INSTALL = YES; @@ -920,6 +928,7 @@ IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_BUNDLE_IDENTIFIER = "co.pNre.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = ExSwiftTests; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = "iphonesimulator iphoneos"; @@ -941,6 +950,7 @@ IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_BUNDLE_IDENTIFIER = "co.pNre.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = ExSwiftTests; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = "iphonesimulator iphoneos"; diff --git a/ExSwift.xcodeproj/xcshareddata/xcschemes/ExSwift-Mac.xcscheme b/ExSwift.xcodeproj/xcshareddata/xcschemes/ExSwift-Mac.xcscheme index 261d65b..83a5561 100644 --- a/ExSwift.xcodeproj/xcshareddata/xcschemes/ExSwift-Mac.xcscheme +++ b/ExSwift.xcodeproj/xcshareddata/xcschemes/ExSwift-Mac.xcscheme @@ -1,6 +1,6 @@ + + + + (items: T...) -> Bool { - return items.all { self.indexOf($0) >= 0 } + return items.all { (item: T) -> Bool in self.indexOf(item) >= 0 } } /** Difference of self and the input arrays. - :param: values Arrays to subtract - :returns: Difference of self and the input arrays + - parameter values: Arrays to subtract + - returns: Difference of self and the input arrays */ func difference (values: [T]...) -> [T] { @@ -54,15 +54,15 @@ internal extension Array { /** Intersection of self and the input arrays. - :param: values Arrays to intersect - :returns: Array of unique values contained in all the dictionaries and self + - parameter values: Arrays to intersect + - returns: Array of unique values contained in all the dictionaries and self */ func intersection (values: [U]...) -> Array { var result = self var intersection = Array() - for (i, value) in enumerate(values) { + for (i, value) in values.enumerate() { // the intersection is computed by intersecting a couple per loop: // self n values[0], (self n values[0]) n values[1], ... @@ -88,8 +88,8 @@ internal extension Array { /** Union of self and the input arrays. - :param: values Arrays - :returns: Union array of unique values + - parameter values: Arrays + - returns: Union array of unique values */ func union (values: [U]...) -> Array { @@ -110,29 +110,29 @@ internal extension Array { /** First element of the array. - :returns: First element of the array if not empty + - returns: First element of the array if not empty */ - @availability(*, unavailable, message="use the 'first' property instead") func first () -> Element? { + @available(*, unavailable, message="use the 'first' property instead") func first () -> Element? { return first } /** Last element of the array. - :returns: Last element of the array if not empty + - returns: Last element of the array if not empty */ - @availability(*, unavailable, message="use the 'last' property instead") func last () -> Element? { + @available(*, unavailable, message="use the 'last' property instead") func last () -> Element? { return last } /** - First occurrence of item, if found. + First occurrence of item, if found. - :param: item The item to search for - :returns: Matched item or nil + - parameter item: The item to search for + - returns: Matched item or nil */ func find (item: U) -> T? { - if let index = indexOf(item) { + if let index: Int = indexOf(item) { return self[index] } @@ -140,10 +140,10 @@ internal extension Array { } /** - First item that meets the condition. + First item that meets the condition. - :param: condition A function which returns a boolean if an element satisfies a given condition or not. - :returns: First matched item or nil + - parameter condition: A function which returns a boolean if an element satisfies a given condition or not. + - returns: First matched item or nil */ func find (condition: Element -> Bool) -> Element? { return takeFirst(condition) @@ -152,28 +152,14 @@ internal extension Array { /** Index of the first occurrence of item, if found. - :param: item The item to search for - :returns: Index of the matched item or nil + - parameter item: The item to search for + - returns: Index of the matched item or nil */ func indexOf (item: U) -> Int? { if item is Element { - return Swift.find(unsafeBitCast(self, [U].self), item) - } - - return nil - } - - /** - Index of the first item that meets the condition. - - :param: condition A function which returns a boolean if an element satisfies a given condition or not. - :returns: Index of the first matched item or nil - */ - func indexOf (condition: Element -> Bool) -> Int? { - for (index, element) in enumerate(self) { - if condition(element) { - return index - } + return self.indexOf({ (object) -> Bool in + return (object as! U) == item + }) } return nil @@ -182,12 +168,12 @@ internal extension Array { /** Gets the index of the last occurrence of item, if found. - :param: item The item to search for - :returns: Index of the matched item or nil + - parameter item: The item to search for + - returns: Index of the matched item or nil */ func lastIndexOf (item: U) -> Int? { if item is Element { - for (index, value) in enumerate(lazy(self).reverse()) { + for (index, value) in lazy(self).reverse().enumerate() { if value as! U == item { return count - 1 - index } @@ -202,8 +188,8 @@ internal extension Array { /** Gets the object at the specified index, if it exists. - :param: index - :returns: Object at index in self + - parameter index: + - returns: Object at index in self */ func get (index: Int) -> Element? { @@ -214,8 +200,8 @@ internal extension Array { /** Gets the objects in the specified range. - :param: range - :returns: Subarray in range + - parameter range: + - returns: Subarray in range */ func get (range: Range) -> Array { @@ -227,8 +213,8 @@ internal extension Array { Returns an array of grouped elements, the first of which contains the first elements of the given arrays, the 2nd contains the 2nd elements of the given arrays, and so on. - :param: arrays Arrays to zip - :returns: Array of grouped elements + - parameter arrays: Arrays to zip + - returns: Array of grouped elements */ func zip (arrays: Any...) -> [[Any?]] { @@ -256,9 +242,9 @@ internal extension Array { Produces an array of arrays, each containing n elements, each offset by step. If the final partition is not n elements long it is dropped. - :param: n The number of elements in each partition. - :param: step The number of elements to progress between each partition. Set to n if not supplied. - :returns: Array partitioned into n element arrays, starting step elements apart. + - parameter n: The number of elements in each partition. + - parameter step: The number of elements to progress between each partition. Set to n if not supplied. + - returns: Array partitioned into n element arrays, starting step elements apart. */ func partition (var n: Int, var step: Int? = nil) -> [Array] { var result = [Array]() @@ -282,12 +268,12 @@ internal extension Array { /** Produces an array of arrays, each containing n elements, each offset by step. - :param: n The number of elements in each partition. - :param: step The number of elements to progress between each partition. Set to n if not supplied. - :param: pad An array of elements to pad the last partition if it is not long enough to + - parameter n: The number of elements in each partition. + - parameter step: The number of elements to progress between each partition. Set to n if not supplied. + - parameter pad: An array of elements to pad the last partition if it is not long enough to contain n elements. If nil is passed or there are not enough pad elements the last partition may less than n elements long. - :returns: Array partitioned into n element arrays, starting step elements apart. + - returns: Array partitioned into n element arrays, starting step elements apart. */ func partition (var n: Int, var step: Int? = nil, pad: Array?) -> [Array] { var result = [Array]() @@ -332,9 +318,9 @@ internal extension Array { /** Produces an array of arrays, each containing n elements, each offset by step. - :param: n The number of elements in each partition. - :param: step The number of elements to progress between each partition. Set to n if not supplied. - :returns: Array partitioned into n element arrays, starting step elements apart. + - parameter n: The number of elements in each partition. + - parameter step: The number of elements to progress between each partition. Set to n if not supplied. + - returns: Array partitioned into n element arrays, starting step elements apart. */ func partitionAll (var n: Int, var step: Int? = nil) -> [Array] { var result = [Array]() @@ -357,8 +343,8 @@ internal extension Array { /** Applies cond to each element in array, splitting it each time cond returns a new value. - :param: cond Function which takes an element and produces an equatable result. - :returns: Array partitioned in order, splitting via results of cond. + - parameter cond: Function which takes an element and produces an equatable result. + - returns: Array partitioned in order, splitting via results of cond. */ func partitionBy (cond: (Element) -> T) -> [Array] { var result = [Array]() @@ -394,7 +380,7 @@ internal extension Array { /** Shuffles the values of the array into a new one - :returns: Shuffled copy of self + - returns: Shuffled copy of self */ func shuffled () -> Array { var shuffled = self @@ -407,8 +393,8 @@ internal extension Array { /** Returns a random subarray of given length. - :param: n Length - :returns: Random subarray of length n + - parameter n: Length + - returns: Random subarray of length n */ func sample (size n: Int = 1) -> Array { if n >= count { @@ -422,33 +408,33 @@ internal extension Array { /** Max value in the current array (if Array.Element implements the Comparable protocol). - :returns: Max value + - returns: Max value */ func max () -> U { - return maxElement(map { + return map { return $0 as! U - }) + }.maxElement()! } /** Min value in the current array (if Array.Element implements the Comparable protocol). - :returns: Min value + - returns: Min value */ func min () -> U { - return minElement(map { + return map { return $0 as! U - }) + }.minElement()! } /** The value for which call(value) is highest. - :returns: Max value in terms of call(value) + - returns: Max value in terms of call(value) */ func maxBy (call: (Element) -> (U)) -> Element? { @@ -473,7 +459,7 @@ internal extension Array { /** The value for which call(value) is lowest. - :returns: Min value in terms of call(value) + - returns: Min value in terms of call(value) */ func minBy (call: (Element) -> (U)) -> Element? { @@ -498,7 +484,7 @@ internal extension Array { /** Iterates on each element of the array. - :param: call Function to call for each element + - parameter call: Function to call for each element */ func each (call: (Element) -> ()) { @@ -511,11 +497,11 @@ internal extension Array { /** Iterates on each element of the array with its index. - :param: call Function to call for each element + - parameter call: Function to call for each element */ func each (call: (Int, Element) -> ()) { - for (index, item) in enumerate(self) { + for (index, item) in self.enumerate() { call(index, item) } @@ -524,19 +510,19 @@ internal extension Array { /** Iterates on each element of the array from Right to Left. - :param: call Function to call for each element + - parameter call: Function to call for each element */ - @availability(*, unavailable, message="use 'reverse().each' instead") func eachRight (call: (Element) -> ()) { + @available(*, unavailable, message="use 'reverse().each' instead") func eachRight (call: (Element) -> ()) { reverse().each(call) } /** Iterates on each element of the array, with its index, from Right to Left. - :param: call Function to call for each element + - parameter call: Function to call for each element */ - @availability(*, unavailable, message="use 'reverse().each' instead") func eachRight (call: (Int, Element) -> ()) { - for (index, item) in enumerate(reverse()) { + @available(*, unavailable, message="use 'reverse().each' instead") func eachRight (call: (Int, Element) -> ()) { + for (index, item) in reverse().enumerate() { call(count - index - 1, item) } } @@ -544,8 +530,8 @@ internal extension Array { /** Checks if test returns true for any element of self. - :param: test Function to call for each element - :returns: true if test returns true for any element of self + - parameter test: Function to call for each element + - returns: true if test returns true for any element of self */ func any (test: (Element) -> Bool) -> Bool { for item in self { @@ -560,8 +546,8 @@ internal extension Array { /** Checks if test returns true for all the elements in self - :param: test Function to call for each element - :returns: True if test returns true for all the elements in self + - parameter test: Function to call for each element + - returns: True if test returns true for all the elements in self */ func all (test: (Element) -> Bool) -> Bool { for item in self { @@ -576,8 +562,8 @@ internal extension Array { /** Opposite of filter. - :param: exclude Function invoked to test elements for the exclusion from the array - :returns: Filtered array + - parameter exclude: Function invoked to test elements for the exclusion from the array + - returns: Filtered array */ func reject (exclude: (Element -> Bool)) -> Array { return filter { @@ -588,8 +574,8 @@ internal extension Array { /** Returns an array containing the first n elements of self. - :param: n Number of elements to take - :returns: First n elements + - parameter n: Number of elements to take + - returns: First n elements */ func take (n: Int) -> Array { return self[0.. Bool) -> Array { var lastTrue = -1 - for (index, value) in enumerate(self) { + for (index, value) in self.enumerate() { if condition(value) { lastTrue = index } else { @@ -620,8 +606,8 @@ internal extension Array { /** Returns the first element in the array to meet the condition. - :param: condition A function which returns a boolean if an element satisfies a given condition or not. - :returns: The first element in the array to meet the condition + - parameter condition: A function which returns a boolean if an element satisfies a given condition or not. + - returns: The first element in the array to meet the condition */ func takeFirst (condition: (Element) -> Bool) -> Element? { @@ -638,8 +624,8 @@ internal extension Array { /** Returns an array containing the the last n elements of self. - :param: n Number of elements to take - :returns: Last n elements + - parameter n: Number of elements to take + - returns: Last n elements */ func tail (n: Int) -> Array { @@ -650,8 +636,8 @@ internal extension Array { /** Subarray from n to the end of the array. - :param: n Number of elements to skip - :returns: Array from n to the end + - parameter n: Number of elements to skip + - returns: Array from n to the end */ func skip (n: Int) -> Array { @@ -662,14 +648,14 @@ internal extension Array { /** Skips the elements of the array up until the condition returns false. - :param: condition A function which returns a boolean if an element satisfies a given condition or not - :returns: Elements of the array starting with the element which does not meet the condition + - parameter condition: A function which returns a boolean if an element satisfies a given condition or not + - returns: Elements of the array starting with the element which does not meet the condition */ func skipWhile (condition: (Element) -> Bool) -> Array { var lastTrue = -1 - for (index, value) in enumerate(self) { + for (index, value) in self.enumerate() { if condition(value) { lastTrue = index } else { @@ -684,7 +670,7 @@ internal extension Array { Costructs an array removing the duplicate values in self if Array.Element implements the Equatable protocol. - :returns: Array of unique values + - returns: Array of unique values */ func unique () -> [T] { var result = [T]() @@ -701,15 +687,15 @@ internal extension Array { /** Returns the set of elements for which call(element) is unique - :param: call The closure to use to determine uniqueness - :returns: The set of elements for which call(element) is unique + - parameter call: The closure to use to determine uniqueness + - returns: The set of elements for which call(element) is unique */ func uniqueBy (call: (Element) -> (T)) -> [Element] { var result: [Element] = [] var uniqueItems: [T] = [] for item in self { - var callResult: T = call(item) + let callResult: T = call(item) if !uniqueItems.contains(callResult) { uniqueItems.append(callResult) result.append(item) @@ -722,11 +708,10 @@ internal extension Array { /** Returns all permutations of a given length within an array - :param: length The length of each permutation - :returns: All permutations of a given length within an array + - parameter length: The length of each permutation + - returns: All permutations of a given length within an array */ func permutation (length: Int) -> [[T]] { - var selfCopy = self if length < 0 || length > self.count { return [] } else if length == 0 { @@ -753,9 +738,9 @@ internal extension Array { } for var i = 0; i < n; i++ { permutationHelper(n - 1, array: &array, endArray: &endArray) - var j = n % 2 == 0 ? i : 0; + let j = n % 2 == 0 ? i : 0; //(array[j], array[n - 1]) = (array[n - 1], array[j]) - var temp: T = array[j] + let temp: T = array[j] array[j] = array[n - 1] array[n - 1] = temp } @@ -767,8 +752,8 @@ internal extension Array { running each element of self through groupingFunction. The corresponding value of each key is an array of the elements responsible for generating the key. - :param: groupingFunction - :returns: Grouped dictionary + - parameter groupingFunction: + - returns: Grouped dictionary */ func groupBy (groupingFunction group: (Element) -> U) -> [U: Array] { @@ -793,8 +778,8 @@ internal extension Array { Similar to groupBy, instead of returning a list of values, returns the number of values for each group. - :param: groupingFunction - :returns: Grouped dictionary + - parameter groupingFunction: + - returns: Grouped dictionary */ func countBy (groupingFunction group: (Element) -> U) -> [U: Int] { @@ -816,19 +801,21 @@ internal extension Array { /** Returns all of the combinations in the array of the given length, allowing repeats - :param: length - :returns: Combinations + - parameter length: + - returns: Combinations */ func repeatedCombination (length: Int) -> [[Element]] { if length < 0 { return [] } + var indexes: [Int] = [] length.times { indexes.append(0) } + var combinations: [[Element]] = [] - var offset = self.count - indexes.count + while true { var combination: [Element] = [] for index in indexes { @@ -853,8 +840,8 @@ internal extension Array { /** Returns all of the combinations in the array of the given length - :param: length - :returns: Combinations + - parameter length: + - returns: Combinations */ func combination (length: Int) -> [[Element]] { if length < 0 || length > self.count { @@ -862,7 +849,7 @@ internal extension Array { } var indexes: [Int] = (0.. [[T]] { @@ -915,8 +902,8 @@ internal extension Array { /** Returns the number of elements which meet the condition - :param: test Function to call for each element - :returns: the number of elements meeting the condition + - parameter test: Function to call for each element + - returns: the number of elements meeting the condition */ func countWhere (test: (Element) -> Bool) -> Int { @@ -943,7 +930,7 @@ internal extension Array { :return: A transposed version of the array, where the object at array[i][j] goes to array[j][i] */ func transposition (array: [[T]]) -> [[T]] { // () -> [[U]] { - var maxWidth: Int = array.map({ $0.count }).max() + let maxWidth: Int = array.map({ $0.count }).max() var transposition = [[T]](count: maxWidth, repeatedValue: []) (0.. () { (0.. (separator: C) -> C? { @@ -986,8 +973,8 @@ internal extension Array { Creates an array with values generated by running each value of self through the mapFunction and discarding nil return values. - :param: mapFunction - :returns: Mapped array + - parameter mapFunction: + - returns: Mapped array */ func mapFilter (mapFunction map: (Element) -> (V)?) -> [V] { @@ -1007,9 +994,9 @@ internal extension Array { Creates an array with values and an accumulated result by running accumulated result and each value of self through the mapFunction. - :param: initial Initial value for accumulator - :param: mapFunction - :returns: Accumulated value and mapped array + - parameter initial: Initial value for accumulator + - parameter mapFunction: + - returns: Accumulated value and mapped array */ func mapAccum (initial: U, mapFunction map: (U, Element) -> (U, V)) -> (U, [V]) { var mapped = [V]() @@ -1038,22 +1025,22 @@ internal extension Array { /** self.reduce from right to left */ - @availability(*, unavailable, message="use 'reverse().reduce' instead") func reduceRight (initial: U, combine: (U, Element) -> U) -> U { + @available(*, unavailable, message="use 'reverse().reduce' instead") func reduceRight (initial: U, combine: (U, Element) -> U) -> U { return reverse().reduce(initial, combine: combine) } /** self.reduceRight with initial value self.last() */ - @availability(*, unavailable, message="use 'reverse().reduce' instead") func reduceRight (combine: (Element, Element) -> Element) -> Element? { + @available(*, unavailable, message="use 'reverse().reduce' instead") func reduceRight (combine: (Element, Element) -> Element) -> Element? { return reverse().reduce(combine) } /** Creates an array with the elements at the specified indexes. - :param: indexes Indexes of the elements to get - :returns: Array with the elements at indexes + - parameter indexes: Indexes of the elements to get + - returns: Array with the elements at indexes */ func at (indexes: Int...) -> Array { return indexes.map { self.get($0)! } @@ -1062,8 +1049,8 @@ internal extension Array { /** Converts the array to a dictionary with the keys supplied via the keySelector. - :param: keySelector - :returns: A dictionary + - parameter keySelector: + - returns: A dictionary */ func toDictionary (keySelector:(Element) -> U) -> [U: Element] { var result: [U: Element] = [:] @@ -1077,8 +1064,8 @@ internal extension Array { /** Converts the array to a dictionary with keys and values supplied via the transform function. - :param: transform - :returns: A dictionary + - parameter transform: + - returns: A dictionary */ func toDictionary (transform: (Element) -> (key: K, value: V)?) -> [K: V] { var result: [K: V] = [:] @@ -1094,7 +1081,7 @@ internal extension Array { /** Flattens a nested Array self to an array of OutType objects. - :returns: Flattened array + - returns: Flattened array */ func flatten () -> [OutType] { var result = [OutType]() @@ -1110,7 +1097,7 @@ internal extension Array { /** Flattens a nested Array self to an array of AnyObject. - :returns: Flattened array + - returns: Flattened array */ func flattenAny () -> [AnyObject] { var result = [AnyObject]() @@ -1129,18 +1116,18 @@ internal extension Array { /** Sorts the array according to the given comparison function. - :param: isOrderedBefore Comparison function. - :returns: An array that is sorted according to the given function + - parameter isOrderedBefore: Comparison function. + - returns: An array that is sorted according to the given function */ - @availability(*, unavailable, message="use 'sorted' instead") func sortBy (isOrderedBefore: (T, T) -> Bool) -> [T] { - return sorted(isOrderedBefore) + @available(*, unavailable, message="use 'sort' instead") func sortBy (isOrderedBefore: (T, T) -> Bool) -> [T] { + return sort(isOrderedBefore) } /** Calls the passed block for each element in the array, either n times or infinitely, if n isn't specified - :param: n the number of times to cycle through - :param: block the block to run for each element in each cycle + - parameter n: the number of times to cycle through + - parameter block: the block to run for each element in each cycle */ func cycle (n: Int? = nil, block: (T) -> ()) { var cyclesRun = 0 @@ -1164,8 +1151,8 @@ internal extension Array { See http://ruby-doc.org/core-2.2.0/Array.html#method-i-bsearch regarding find-minimum mode for more - :param: block the block to run each time - :returns: the min element, or nil if there are no items for which the block returns true + - parameter block: the block to run each time + - returns: the min element, or nil if there are no items for which the block returns true */ func bSearch (block: (T) -> (Bool)) -> T? { if count == 0 { @@ -1175,7 +1162,7 @@ internal extension Array { var low = 0 var high = count - 1 while low <= high { - var mid = low + (high - low) / 2 + let mid = low + (high - low) / 2 if block(self[mid]) { if mid == 0 || !block(self[mid - 1]) { return self[mid] @@ -1198,8 +1185,8 @@ internal extension Array { See http://ruby-doc.org/core-2.2.0/Array.html#method-i-bsearch regarding find-any mode for more - :param: block the block to run each time - :returns: an item (there could be multiple matches) for which the block returns true + - parameter block: the block to run each time + - returns: an item (there could be multiple matches) for which the block returns true */ func bSearch (block: (T) -> (Int)) -> T? { let match = bSearch { item in @@ -1215,17 +1202,17 @@ internal extension Array { /** Sorts the array by the value returned from the block, in ascending order - :param: block the block to use to sort by - :returns: an array sorted by that block, in ascending order + - parameter block: the block to use to sort by + - returns: an array sorted by that block, in ascending order */ func sortUsing (block: ((T) -> U)) -> [T] { - return self.sorted({ block($0.0) < block($0.1) }) + return self.sort({ block($0.0) < block($0.1) }) } /** Removes the last element from self and returns it. - :returns: The removed element + - returns: The removed element */ mutating func pop () -> Element? { @@ -1240,7 +1227,7 @@ internal extension Array { /** Same as append. - :param: newElement Element to append + - parameter newElement: Element to append */ mutating func push (newElement: Element) { return append(newElement) @@ -1249,7 +1236,7 @@ internal extension Array { /** Returns the first element of self and removes it from the array. - :returns: The removed element + - returns: The removed element */ mutating func shift () -> Element? { @@ -1264,7 +1251,7 @@ internal extension Array { /** Prepends an object to the array. - :param: newElement Object to prepend + - parameter newElement: Object to prepend */ mutating func unshift (newElement: Element) { insert(newElement, atIndex: 0) @@ -1273,8 +1260,8 @@ internal extension Array { /** Inserts an array at a given index in self. - :param: newArray Array to insert - :param: atIndex Where to insert the array + - parameter newArray: Array to insert + - parameter atIndex: Where to insert the array */ mutating func insert (newArray: Array, atIndex: Int) { self = take(atIndex) + newArray + skip(atIndex) @@ -1283,7 +1270,7 @@ internal extension Array { /** Deletes all the items in self that are equal to element. - :param: element Element to remove + - parameter element: Element to remove */ mutating func remove (element: U) { let anotherSelf = self @@ -1301,20 +1288,20 @@ internal extension Array { /** Constructs an array containing the values in the given range. - :param: range - :returns: Array of values + - parameter range: + - returns: Array of values */ - @availability(*, unavailable, message="use the '[U](range)' constructor") static func range (range: Range) -> [U] { + @available(*, unavailable, message="use the '[U](range)' constructor") static func range (range: Range) -> [U] { return [U](range) } /** Returns the subarray in the given range. - :param: range Range of the subarray elements - :returns: Subarray or nil if the index is out of bounds + - parameter range: Range of the subarray elements + - returns: Subarray or nil if the index is out of bounds */ - subscript (#rangeAsArray: Range) -> Array { + subscript (rangeAsArray rangeAsArray: Range) -> Array { // Fix out of bounds indexes let start = Swift.max(0, rangeAsArray.startIndex) let end = Swift.min(rangeAsArray.endIndex, count) @@ -1329,8 +1316,8 @@ internal extension Array { /** Returns a subarray whose items are in the given interval in self. - :param: interval Interval of indexes of the subarray elements - :returns: Subarray or nil if the index is out of bounds + - parameter interval: Interval of indexes of the subarray elements + - returns: Subarray or nil if the index is out of bounds */ subscript (interval: HalfOpenInterval) -> Array { return self[rangeAsArray: Range(start: interval.start, end: interval.end)] @@ -1339,8 +1326,8 @@ internal extension Array { /** Returns a subarray whose items are in the given interval in self. - :param: interval Interval of indexes of the subarray elements - :returns: Subarray or nil if the index is out of bounds + - parameter interval: Interval of indexes of the subarray elements + - returns: Subarray or nil if the index is out of bounds */ subscript (interval: ClosedInterval) -> Array { return self[rangeAsArray: Range(start: interval.start, end: interval.end + 1)] @@ -1349,10 +1336,10 @@ internal extension Array { /** Creates an array with the elements at indexes in the given list of integers. - :param: first First index - :param: second Second index - :param: rest Rest of indexes - :returns: Array with the items at the specified indexes + - parameter first: First index + - parameter second: Second index + - parameter rest: Rest of indexes + - returns: Array with the items at the specified indexes */ subscript (first: Int, second: Int, rest: Int...) -> Array { let indexes = [first, second] + rest @@ -1391,9 +1378,9 @@ public func | (first: [T], second: [T]) -> [T] { /** Array duplication. - :param: array Array to duplicate - :param: n How many times the array must be repeated - :returns: Array of repeated values + - parameter array: Array to duplicate + - parameter n: How many times the array must be repeated + - returns: Array of repeated values */ public func * (array: [ItemType], n: Int) -> [ItemType] { @@ -1406,14 +1393,3 @@ public func * (array: [ItemType], n: Int) -> [ItemType] { return result } - -/** - Array items concatenation à la Ruby. - - :param: array Array of Strings to join - :param: separator Separator to join the array elements - :returns: Joined string -*/ -public func * (array: [String], separator: String) -> String { - return array.implode(separator)! -} diff --git a/ExSwift/Character.swift b/ExSwift/Character.swift index e3f0c11..2b1ba82 100644 --- a/ExSwift/Character.swift +++ b/ExSwift/Character.swift @@ -15,7 +15,7 @@ public extension Character { the corresponding integer. */ public func toInt () -> Int? { - return String(self).toInt() + return Int(String(self)) } } \ No newline at end of file diff --git a/ExSwift/Dictionary.swift b/ExSwift/Dictionary.swift index 671026a..d6cc7da 100644 --- a/ExSwift/Dictionary.swift +++ b/ExSwift/Dictionary.swift @@ -15,8 +15,8 @@ internal extension Dictionary { Difference of self and the input dictionaries. Two dictionaries are considered equal if they contain the same [key: value] pairs. - :param: dictionaries Dictionaries to subtract - :returns: Difference of self and the input dictionaries + - parameter dictionaries: Dictionaries to subtract + - returns: Difference of self and the input dictionaries */ func difference (dictionaries: [Key: V]...) -> [Key: V] { @@ -44,8 +44,8 @@ internal extension Dictionary { /** Union of self and the input dictionaries. - :param: dictionaries Dictionaries to join - :returns: Union of self and the input dictionaries + - parameter dictionaries: Dictionaries to join + - returns: Union of self and the input dictionaries */ func union (dictionaries: Dictionary...) -> Dictionary { @@ -65,8 +65,8 @@ internal extension Dictionary { Intersection of self and the input dictionaries. Two dictionaries are considered equal if they contain the same [key: value] copules. - :param: values Dictionaries to intersect - :returns: Dictionary of [key: value] couples contained in all the dictionaries and self + - parameter values: Dictionaries to intersect + - returns: Dictionary of [key: value] couples contained in all the dictionaries and self */ func intersection (dictionaries: [K: V]...) -> [K: V] { @@ -90,8 +90,8 @@ internal extension Dictionary { /** Checks if a key exists in the dictionary. - :param: key Key to check - :returns: true if the key exists + - parameter key: Key to check + - returns: true if the key exists */ func has (key: Key) -> Bool { return indexForKey(key) != nil @@ -101,8 +101,8 @@ internal extension Dictionary { Creates an Array with values generated by running each [key: value] of self through the mapFunction. - :param: mapFunction - :returns: Mapped array + - parameter mapFunction: + - returns: Mapped array */ func toArray (map: (Key, Value) -> V) -> [V] { @@ -120,8 +120,8 @@ internal extension Dictionary { Creates a Dictionary with the same keys as self and values generated by running each [key: value] of self through the mapFunction. - :param: mapFunction - :returns: Mapped dictionary + - parameter mapFunction: + - returns: Mapped dictionary */ func mapValues (map: (Key, Value) -> V) -> [Key: V] { @@ -139,8 +139,8 @@ internal extension Dictionary { 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. - :param: mapFunction - :returns: Mapped dictionary + - parameter mapFunction: + - returns: Mapped dictionary */ func mapFilterValues (map: (Key, Value) -> V?) -> [Key: V] { @@ -160,8 +160,8 @@ internal extension Dictionary { Creates a Dictionary with keys and values generated by running each [key: value] of self through the mapFunction discarding nil return values. - :param: mapFunction - :returns: Mapped dictionary + - parameter mapFunction: + - returns: Mapped dictionary */ func mapFilter (map: (Key, Value) -> (K, V)?) -> [K: V] { @@ -181,8 +181,8 @@ internal extension Dictionary { Creates a Dictionary with keys and values generated by running each [key: value] of self through the mapFunction. - :param: mapFunction - :returns: Mapped dictionary + - parameter mapFunction: + - returns: Mapped dictionary */ func map (map: (Key, Value) -> (K, V)) -> [K: V] { @@ -200,7 +200,7 @@ internal extension Dictionary { /** Loops trough each [key: value] pair in self. - :param: eachFunction Function to inovke on each loop + - parameter eachFunction: Function to inovke on each loop */ func each (each: (Key, Value) -> ()) { @@ -214,8 +214,8 @@ internal extension Dictionary { Constructs a dictionary containing every [key: value] pair from self for which testFunction evaluates to true. - :param: testFunction Function called to test each key, value - :returns: Filtered dictionary + - parameter testFunction: Function called to test each key, value + - returns: Filtered dictionary */ func filter (test: (Key, Value) -> Bool) -> Dictionary { @@ -236,8 +236,8 @@ internal extension Dictionary { running each element of self through groupingFunction. The corresponding value of each key is an array of the elements responsible for generating the key. - :param: groupingFunction - :returns: Grouped dictionary + - parameter groupingFunction: + - returns: Grouped dictionary */ func groupBy (group: (Key, Value) -> T) -> [T: [Value]] { @@ -262,8 +262,8 @@ internal extension Dictionary { /** Similar to groupBy. Doesn't return a list of values, but the number of values for each group. - :param: groupingFunction Function called to define the grouping key - :returns: Grouped dictionary + - parameter groupingFunction: Function called to define the grouping key + - returns: Grouped dictionary */ func countBy (group: (Key, Value) -> (T)) -> [T: Int] { @@ -287,8 +287,8 @@ internal extension Dictionary { /** Checks if test evaluates true for all the elements in self. - :param: test Function to call for each element - :returns: true if test returns true for all the elements in self + - parameter test: Function to call for each element + - returns: true if test returns true for all the elements in self */ func all (test: (Key, Value) -> (Bool)) -> Bool { @@ -305,8 +305,8 @@ internal extension Dictionary { /** Checks if test evaluates true for any element of self. - :param: test Function to call for each element - :returns: true if test returns true for any element of self + - parameter test: Function to call for each element + - returns: true if test returns true for any element of self */ func any (test: (Key, Value) -> (Bool)) -> Bool { @@ -324,8 +324,8 @@ internal extension Dictionary { /** Returns the number of elements which meet the condition - :param: test Function to call for each element - :returns: the number of elements meeting the condition + - parameter test: Function to call for each element + - returns: the number of elements meeting the condition */ func countWhere (test: (Key, Value) -> (Bool)) -> Int { @@ -340,23 +340,11 @@ internal extension Dictionary { return result } - - /** - Recombines the [key: value] couples in self trough combine using initial as initial value. - - :param: initial Initial value - :param: combine Function that reduces the dictionary - :returns: Resulting value - */ - func reduce (initial: U, combine: (U, Element) -> U) -> U { - return Swift.reduce(self, initial, combine) - } - /** Returns a copy of self, filtered to only have values for the whitelisted keys. - :param: keys Whitelisted keys - :returns: Filtered dictionary + - parameter keys: Whitelisted keys + - returns: Filtered dictionary */ func pick (keys: [Key]) -> Dictionary { return filter { (key: Key, _) -> Bool in @@ -367,8 +355,8 @@ internal extension Dictionary { /** Returns a copy of self, filtered to only have values for the whitelisted keys. - :param: keys Whitelisted keys - :returns: Filtered dictionary + - parameter keys: Whitelisted keys + - returns: Filtered dictionary */ func pick (keys: Key...) -> Dictionary { return pick(unsafeBitCast(keys, [Key].self)) @@ -377,8 +365,8 @@ internal extension Dictionary { /** Returns a copy of self, filtered to only have values for the whitelisted keys. - :param: keys Keys to get - :returns: Dictionary with the given keys + - parameter keys: Keys to get + - returns: Dictionary with the given keys */ func at (keys: Key...) -> Dictionary { return pick(keys) @@ -388,7 +376,7 @@ internal extension Dictionary { Removes a (key, value) pair from self and returns it as tuple. If the dictionary is empty returns nil. - :returns: (key, value) tuple + - returns: (key, value) tuple */ mutating func shift () -> (Key, Value)? { if let key = keys.first { diff --git a/ExSwift/Double.swift b/ExSwift/Double.swift index 9acfaf6..ace4b9e 100644 --- a/ExSwift/Double.swift +++ b/ExSwift/Double.swift @@ -13,7 +13,7 @@ public extension Double { /** Absolute value. - :returns: fabs(self) + - returns: fabs(self) */ func abs () -> Double { return Foundation.fabs(self) @@ -22,7 +22,7 @@ public extension Double { /** Squared root. - :returns: sqrt(self) + - returns: sqrt(self) */ func sqrt () -> Double { return Foundation.sqrt(self) @@ -31,7 +31,7 @@ public extension Double { /** Rounds self to the largest integer <= self. - :returns: floor(self) + - returns: floor(self) */ func floor () -> Double { return Foundation.floor(self) @@ -40,7 +40,7 @@ public extension Double { /** Rounds self to the smallest integer >= self. - :returns: ceil(self) + - returns: ceil(self) */ func ceil () -> Double { return Foundation.ceil(self) @@ -49,7 +49,7 @@ public extension Double { /** Rounds self to the nearest integer. - :returns: round(self) + - returns: round(self) */ func round () -> Double { return Foundation.round(self) @@ -58,9 +58,9 @@ public extension Double { /** Clamps self to a specified range. - :param: min Lower bound - :param: max Upper bound - :returns: Clamped value + - parameter min: Lower bound + - parameter max: Upper bound + - returns: Clamped value */ func clamp (min: Double, _ max: Double) -> Double { return Swift.max(min, Swift.min(max, self)) @@ -82,7 +82,7 @@ public extension Double { :params: min :params: max - :returns: Random number + - returns: Random number */ static func random(min: Double = 0, max: Double) -> Double { let diff = max - min; diff --git a/ExSwift/ExSwift.swift b/ExSwift/ExSwift.swift index 82c5dc0..6060c7b 100644 --- a/ExSwift/ExSwift.swift +++ b/ExSwift/ExSwift.swift @@ -20,9 +20,9 @@ public class ExSwift { /** Creates a wrapper that, executes function only after being called n times. - :param: n No. of times the wrapper has to be called before function is invoked - :param: function Function to wrap - :returns: Wrapper function + - parameter n: No. of times the wrapper has to be called before function is invoked + - parameter function: Function to wrap + - returns: Wrapper function */ public class func after (n: Int, function: (P...) -> T) -> ((P...) -> T?) { @@ -48,9 +48,9 @@ public class ExSwift { /** Creates a wrapper that, executes function only after being called n times - :param: n No. of times the wrapper has to be called before function is invoked - :param: function Function to wrap - :returns: Wrapper function + - parameter n: No. of times the wrapper has to be called before function is invoked + - parameter function: Function to wrap + - returns: Wrapper function */ public class func after (n: Int, function: Void -> T) -> (Void -> T?) { func callAfter (args: Any?...) -> T { @@ -66,8 +66,8 @@ public class ExSwift { Creates a wrapper function that invokes function once. Repeated calls to the wrapper function will return the value of the first call. - :param: function Function to wrap - :returns: Wrapper function + - parameter function: Function to wrap + - returns: Wrapper function */ public class func once (function: (P...) -> T) -> ((P...) -> T) { @@ -94,8 +94,8 @@ public class ExSwift { Creates a wrapper function that invokes function once. Repeated calls to the wrapper function will return the value of the first call. - :param: function Function to wrap - :returns: Wrapper function + - parameter function: Function to wrap + - returns: Wrapper function */ public class func once (function: Void -> T) -> (Void -> T) { let f = ExSwift.once { @@ -110,9 +110,9 @@ public class ExSwift { Creates a wrapper that, when called, invokes function with any additional partial arguments prepended to those provided to the new function. - :param: function Function to wrap - :param: parameters Arguments to prepend - :returns: Wrapper function + - parameter function: Function to wrap + - parameter parameters: Arguments to prepend + - returns: Wrapper function */ public class func partial (function: (P...) -> T, _ parameters: P...) -> ((P...) -> T) { typealias Function = [P] -> T @@ -127,9 +127,9 @@ public class ExSwift { Creates a wrapper (without any parameter) that, when called, invokes function automatically passing parameters as arguments. - :param: function Function to wrap - :param: parameters Arguments to pass to function - :returns: Wrapper function + - parameter function: Function to wrap + - parameter parameters: Arguments to pass to function + - returns: Wrapper function */ public class func bind (function: (P...) -> T, _ parameters: P...) -> (Void -> T) { typealias Function = [P] -> T @@ -143,8 +143,8 @@ public class ExSwift { /** Creates a wrapper for function that caches the result of function's invocations. - :param: function Function with one parameter to cache - :returns: Wrapper function + - parameter function: Function with one parameter to cache + - returns: Wrapper function */ public class func cached (function: P -> R) -> (P -> R) { var cache = [P:R]() @@ -165,9 +165,9 @@ public class ExSwift { /** Creates a wrapper for function that caches the result of function's invocations. - :param: function Function to cache - :param: hash Parameters based hashing function that computes the key used to store each result in the cache - :returns: Wrapper function + - parameter function: Function to cache + - parameter hash: Parameters based hashing function that computes the key used to store each result in the cache + - returns: Wrapper function */ public class func cached (function: (P...) -> R, hash: ((P...) -> P)) -> ((P...) -> R) { typealias Function = [P] -> R @@ -194,8 +194,8 @@ public class ExSwift { /** Creates a wrapper for function that caches the result of function's invocations. - :param: function Function to cache - :returns: Wrapper function + - parameter function: Function to cache + - returns: Wrapper function */ public class func cached (function: (P...) -> R) -> ((P...) -> R) { return cached(function, hash: { (params: P...) -> P in return params[0] }) @@ -204,11 +204,11 @@ public class ExSwift { /** Utility method to return an NSRegularExpression object given a pattern. - :param: pattern Regex pattern - :param: ignoreCase If true the NSRegularExpression is created with the NSRegularExpressionOptions.CaseInsensitive flag - :returns: NSRegularExpression object + - parameter pattern: Regex pattern + - parameter ignoreCase: If true the NSRegularExpression is created with the NSRegularExpressionOptions.CaseInsensitive flag + - returns: NSRegularExpression object */ - internal class func regex (pattern: String, ignoreCase: Bool = false) -> NSRegularExpression? { + internal class func regex (pattern: String, ignoreCase: Bool = false) throws -> NSRegularExpression? { var options = NSRegularExpressionOptions.DotMatchesLineSeparators.rawValue @@ -216,13 +216,10 @@ public class ExSwift { options = NSRegularExpressionOptions.CaseInsensitive.rawValue | options } - var error: NSError? = nil - let regex = NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions(rawValue: options), error: &error) - - return (error == nil) ? regex : nil + return try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions(rawValue: options)) } - + } func <=> (lhs: T, rhs: T) -> Int { @@ -256,14 +253,13 @@ extension ExSwift { result.append(obj) } else if reflection.disposition == .ObjCObject { - var bridgedValue: T!? - // If it is an NSArray, flattening will produce the expected result if let array = object as? NSArray { result += array.flatten() } else if let bridged = reflection.value as? T { result.append(bridged) } + } else if reflection.disposition == .IndexContainer { // object is a native Swift array diff --git a/ExSwift/Float.swift b/ExSwift/Float.swift index 8951f36..3362f60 100644 --- a/ExSwift/Float.swift +++ b/ExSwift/Float.swift @@ -13,7 +13,7 @@ public extension Float { /** Absolute value. - :returns: fabs(self) + - returns: fabs(self) */ func abs () -> Float { return fabsf(self) @@ -22,7 +22,7 @@ public extension Float { /** Squared root. - :returns: sqrtf(self) + - returns: sqrtf(self) */ func sqrt () -> Float { return sqrtf(self) @@ -31,7 +31,7 @@ public extension Float { /** Rounds self to the largest integer <= self. - :returns: floorf(self) + - returns: floorf(self) */ func floor () -> Float { return floorf(self) @@ -40,7 +40,7 @@ public extension Float { /** Rounds self to the smallest integer >= self. - :returns: ceilf(self) + - returns: ceilf(self) */ func ceil () -> Float { return ceilf(self) @@ -49,7 +49,7 @@ public extension Float { /** Rounds self to the nearest integer. - :returns: roundf(self) + - returns: roundf(self) */ func round () -> Float { return roundf(self) @@ -58,9 +58,9 @@ public extension Float { /** Clamps self to a specified range. - :param: min Lower bound - :param: max Upper bound - :returns: Clamped value + - parameter min: Lower bound + - parameter max: Upper bound + - returns: Clamped value */ func clamp (min: Float, _ max: Float) -> Float { return Swift.max(min, Swift.min(max, self)) @@ -69,9 +69,9 @@ public extension Float { /** Random float between min and max (inclusive). - :param: min - :param: max - :returns: Random number + - parameter min: + - parameter max: + - returns: Random number */ static func random(min: Float = 0, max: Float) -> Float { let diff = max - min; diff --git a/ExSwift/Info.plist b/ExSwift/Info.plist index 3242e58..144df05 100644 --- a/ExSwift/Info.plist +++ b/ExSwift/Info.plist @@ -7,7 +7,7 @@ CFBundleExecutable ${EXECUTABLE_NAME} CFBundleIdentifier - co.pNre.${PRODUCT_NAME:rfc1034identifier} + $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName diff --git a/ExSwift/Int.swift b/ExSwift/Int.swift index 26d3ddd..5503fe5 100644 --- a/ExSwift/Int.swift +++ b/ExSwift/Int.swift @@ -13,7 +13,7 @@ public extension Int { /** Calls function self times. - :param: function Function to call + - parameter function: Function to call */ func times (function: Void -> T) { (0.. Void) { (0.. (function: (Int) -> T) { (0.. Bool { return (self % 2) == 0 @@ -49,7 +49,7 @@ public extension Int { /** Checks if a number is odd. - :returns: true if self is odd + - returns: true if self is odd */ func isOdd () -> Bool { return !isEven() @@ -58,8 +58,8 @@ public extension Int { /** Iterates function, passing in integer values from self up to and including limit. - :param: limit Last value to pass - :param: function Function to invoke + - parameter limit: Last value to pass + - parameter function: Function to invoke */ func upTo (limit: Int, function: (Int) -> ()) { if limit < self { @@ -72,22 +72,22 @@ public extension Int { /** Iterates function, passing in integer values from self down to and including limit. - :param: limit Last value to pass - :param: function Function to invoke + - parameter limit: Last value to pass + - parameter function: Function to invoke */ func downTo (limit: Int, function: (Int) -> ()) { if limit > self { return } - Array(limit...self).reverse().each(function) + Array(Array(limit...self).reverse()).each(function) } /** Clamps self to a specified range. - :param: range Clamping range - :returns: Clamped value + - parameter range: Clamping range + - returns: Clamped value */ func clamp (range: Range) -> Int { return clamp(range.startIndex, range.endIndex - 1) @@ -96,9 +96,9 @@ public extension Int { /** Clamps self to a specified range. - :param: min Lower bound - :param: max Upper bound - :returns: Clamped value + - parameter min: Lower bound + - parameter max: Upper bound + - returns: Clamped value */ func clamp (min: Int, _ max: Int) -> Int { return Swift.max(min, Swift.min(max, self)) @@ -107,9 +107,9 @@ public extension Int { /** Checks if self is included a specified range. - :param: range Range - :param: strict If true, "<" is used for comparison - :returns: true if in range + - parameter range: Range + - parameter strict: If true, "<" is used for comparison + - returns: true if in range */ func isIn (range: Range, strict: Bool = false) -> Bool { if strict { @@ -122,8 +122,8 @@ public extension Int { /** Checks if self is included in a closed interval. - :param: interval Interval to check - :returns: true if in the interval + - parameter interval: Interval to check + - returns: true if in the interval */ func isIn (interval: ClosedInterval) -> Bool { return interval.contains(self) @@ -132,8 +132,8 @@ public extension Int { /** Checks if self is included in an half open interval. - :param: interval Interval to check - :returns: true if in the interval + - parameter interval: Interval to check + - returns: true if in the interval */ func isIn (interval: HalfOpenInterval) -> Bool { return interval.contains(self) @@ -147,9 +147,9 @@ public extension Int { func digits () -> [Int] { var result = [Int]() - for char in String(self) { + for char in String(self).characters { let string = String(char) - if let toInt = string.toInt() { + if let toInt = Int(string) { result.append(toInt) } } @@ -160,7 +160,7 @@ public extension Int { /** Absolute value. - :returns: abs(self) + - returns: abs(self) */ func abs () -> Int { return Swift.abs(self) @@ -169,8 +169,8 @@ public extension Int { /** Greatest common divisor of self and n. - :param: n - :returns: GCD + - parameter n: + - returns: GCD */ func gcd (n: Int) -> Int { return n == 0 ? self : n.gcd(self % n) @@ -179,8 +179,8 @@ public extension Int { /** Least common multiple of self and n - :param: n - :returns: LCM + - parameter n: + - returns: LCM */ func lcm (n: Int) -> Int { return (self * n).abs() / gcd(n) @@ -189,7 +189,7 @@ public extension Int { /** Computes the factorial of self - :returns: Factorial + - returns: Factorial */ func factorial () -> Int { return self == 0 ? 1 : self * (self - 1).factorial() @@ -198,9 +198,9 @@ public extension Int { /** Random integer between min and max (inclusive). - :param: min Minimum value to return - :param: max Maximum value to return - :returns: Random integer + - parameter min: Minimum value to return + - parameter max: Maximum value to return + - returns: Random integer */ static func random(min: Int = 0, max: Int) -> Int { return Int(arc4random_uniform(UInt32((max - min) + 1))) + min diff --git a/ExSwift/NSArray.swift b/ExSwift/NSArray.swift index d2c3a9e..ca2d23d 100644 --- a/ExSwift/NSArray.swift +++ b/ExSwift/NSArray.swift @@ -13,7 +13,7 @@ public extension NSArray { /** Converts an NSArray object to an OutType[] array containing the items in the NSArray of type OutType. - :returns: Array of Swift objects + - returns: Array of Swift objects */ func cast () -> [OutType] { var result = [OutType]() @@ -29,7 +29,7 @@ public extension NSArray { Flattens a multidimensional NSArray to an OutType[] array containing the items in the NSArray that can be bridged from their ObjC type to OutType. - :returns: Flattened array + - returns: Flattened array */ func flatten () -> [OutType] { var result = [OutType]() @@ -45,7 +45,7 @@ public extension NSArray { /** Flattens a multidimensional NSArray to a [AnyObject]. - :returns: Flattened array + - returns: Flattened array */ func flattenAny () -> [AnyObject] { var result = [AnyObject]() diff --git a/ExSwift/NSDate.swift b/ExSwift/NSDate.swift index 50d758e..6f8e38d 100644 --- a/ExSwift/NSDate.swift +++ b/ExSwift/NSDate.swift @@ -15,66 +15,66 @@ public extension NSDate { /** Returns a new NSDate object representing the date calculated by adding the amount specified to self date - :param: seconds number of seconds to add - :param: minutes number of minutes to add - :param: hours number of hours to add - :param: days number of days to add - :param: weeks number of weeks to add - :param: months number of months to add - :param: years number of years to add - :returns: the NSDate computed + - parameter seconds: number of seconds to add + - parameter minutes: number of minutes to add + - parameter hours: number of hours to add + - parameter days: number of days to add + - parameter weeks: number of weeks to add + - parameter months: number of months to add + - parameter years: number of years to add + - returns: the NSDate computed */ - public func add(seconds: Int = 0, minutes: Int = 0, hours: Int = 0, days: Int = 0, weeks: Int = 0, months: Int = 0, years: Int = 0) -> NSDate { - var calendar = NSCalendar.currentCalendar() - + public func add(seconds seconds: Int = 0, minutes: Int = 0, hours: Int = 0, days: Int = 0, weeks: Int = 0, months: Int = 0, years: Int = 0) -> NSDate { + let calendar = NSCalendar.currentCalendar() let version = floor(NSFoundationVersionNumber) if version <= NSFoundationVersionNumber10_9_2 { var component = NSDateComponents() - component.setValue(seconds, forComponent: .CalendarUnitSecond) + component.setValue(seconds, forComponent: .Second) - var date : NSDate! = calendar.dateByAddingComponents(component, toDate: self, options: nil)! + var date : NSDate! = calendar.dateByAddingComponents(component, toDate: self, options: [])! component = NSDateComponents() - component.setValue(minutes, forComponent: .CalendarUnitMinute) - date = calendar.dateByAddingComponents(component, toDate: date, options: nil)! + component.setValue(minutes, forComponent: .Minute) + date = calendar.dateByAddingComponents(component, toDate: date, options: [])! component = NSDateComponents() - component.setValue(hours, forComponent: .CalendarUnitHour) - date = calendar.dateByAddingComponents(component, toDate: date, options: nil)! + component.setValue(hours, forComponent: .Hour) + date = calendar.dateByAddingComponents(component, toDate: date, options: [])! component = NSDateComponents() - component.setValue(days, forComponent: .CalendarUnitDay) - date = calendar.dateByAddingComponents(component, toDate: date, options: nil)! + component.setValue(days, forComponent: .Day) + date = calendar.dateByAddingComponents(component, toDate: date, options: [])! component = NSDateComponents() - component.setValue(weeks, forComponent: .CalendarUnitWeekOfMonth) - date = calendar.dateByAddingComponents(component, toDate: date, options: nil)! + component.setValue(weeks, forComponent: .WeekOfMonth) + date = calendar.dateByAddingComponents(component, toDate: date, options: [])! component = NSDateComponents() - component.setValue(months, forComponent: .CalendarUnitMonth) - date = calendar.dateByAddingComponents(component, toDate: date, options: nil)! + component.setValue(months, forComponent: .Month) + date = calendar.dateByAddingComponents(component, toDate: date, options: [])! component = NSDateComponents() - component.setValue(years, forComponent: .CalendarUnitYear) - date = calendar.dateByAddingComponents(component, toDate: date, options: nil)! + component.setValue(years, forComponent: .Year) + date = calendar.dateByAddingComponents(component, toDate: date, options: [])! return date } - - var date : NSDate! = calendar.dateByAddingUnit(.CalendarUnitSecond, value: seconds, toDate: self, options: nil) - date = calendar.dateByAddingUnit(.CalendarUnitMinute, value: minutes, toDate: date, options: nil) - date = calendar.dateByAddingUnit(.CalendarUnitDay, value: days, toDate: date, options: nil) - date = calendar.dateByAddingUnit(.CalendarUnitHour, value: hours, toDate: date, options: nil) - date = calendar.dateByAddingUnit(.CalendarUnitWeekOfMonth, value: weeks, toDate: date, options: nil) - date = calendar.dateByAddingUnit(.CalendarUnitMonth, value: months, toDate: date, options: nil) - date = calendar.dateByAddingUnit(.CalendarUnitYear, value: years, toDate: date, options: nil) + + let options = NSCalendarOptions(rawValue: 0) + var date : NSDate! = calendar.dateByAddingUnit(NSCalendarUnit.Second, value: seconds, toDate: self, options: options) + date = calendar.dateByAddingUnit(NSCalendarUnit.Minute, value: minutes, toDate: date, options: options) + date = calendar.dateByAddingUnit(NSCalendarUnit.Day, value: days, toDate: date, options: options) + date = calendar.dateByAddingUnit(NSCalendarUnit.Hour, value: hours, toDate: date, options: options) + date = calendar.dateByAddingUnit(NSCalendarUnit.WeekOfMonth, value: weeks, toDate: date, options: options) + date = calendar.dateByAddingUnit(NSCalendarUnit.Month, value: months, toDate: date, options: options) + date = calendar.dateByAddingUnit(NSCalendarUnit.Year, value: years, toDate: date, options: options) return date } /** Returns a new NSDate object representing the date calculated by adding an amount of seconds to self date - :param: seconds number of seconds to add - :returns: the NSDate computed + - parameter seconds: number of seconds to add + - returns: the NSDate computed */ public func addSeconds (seconds: Int) -> NSDate { return add(seconds: seconds) @@ -83,8 +83,8 @@ public extension NSDate { /** Returns a new NSDate object representing the date calculated by adding an amount of minutes to self date - :param: minutes number of minutes to add - :returns: the NSDate computed + - parameter minutes: number of minutes to add + - returns: the NSDate computed */ public func addMinutes (minutes: Int) -> NSDate { return add(minutes: minutes) @@ -93,8 +93,8 @@ public extension NSDate { /** Returns a new NSDate object representing the date calculated by adding an amount of hours to self date - :param: hours number of hours to add - :returns: the NSDate computed + - parameter hours: number of hours to add + - returns: the NSDate computed */ public func addHours(hours: Int) -> NSDate { return add(hours: hours) @@ -103,8 +103,8 @@ public extension NSDate { /** Returns a new NSDate object representing the date calculated by adding an amount of days to self date - :param: days number of days to add - :returns: the NSDate computed + - parameter days: number of days to add + - returns: the NSDate computed */ public func addDays(days: Int) -> NSDate { return add(days: days) @@ -113,8 +113,8 @@ public extension NSDate { /** Returns a new NSDate object representing the date calculated by adding an amount of weeks to self date - :param: weeks number of weeks to add - :returns: the NSDate computed + - parameter weeks: number of weeks to add + - returns: the NSDate computed */ public func addWeeks(weeks: Int) -> NSDate { return add(weeks: weeks) @@ -124,8 +124,8 @@ public extension NSDate { /** Returns a new NSDate object representing the date calculated by adding an amount of months to self date - :param: months number of months to add - :returns: the NSDate computed + - parameter months: number of months to add + - returns: the NSDate computed */ public func addMonths(months: Int) -> NSDate { @@ -135,8 +135,8 @@ public extension NSDate { /** Returns a new NSDate object representing the date calculated by adding an amount of years to self date - :param: years number of year to add - :returns: the NSDate computed + - parameter years: number of year to add + - returns: the NSDate computed */ public func addYears(years: Int) -> NSDate { return add(years: years) @@ -147,8 +147,8 @@ public extension NSDate { /** Checks if self is after input NSDate - :param: date NSDate to compare - :returns: True if self is after the input NSDate, false otherwise + - parameter date: NSDate to compare + - returns: True if self is after the input NSDate, false otherwise */ public func isAfter(date: NSDate) -> Bool{ return (self.compare(date) == NSComparisonResult.OrderedDescending) @@ -157,8 +157,8 @@ public extension NSDate { /** Checks if self is before input NSDate - :param: date NSDate to compare - :returns: True if self is before the input NSDate, false otherwise + - parameter date: NSDate to compare + - returns: True if self is before the input NSDate, false otherwise */ public func isBefore(date: NSDate) -> Bool{ return (self.compare(date) == NSComparisonResult.OrderedAscending) @@ -172,7 +172,7 @@ public extension NSDate { */ public var year : Int { get { - return getComponent(.CalendarUnitYear) + return getComponent(.Year) } } @@ -181,7 +181,7 @@ public extension NSDate { */ public var month : Int { get { - return getComponent(.CalendarUnitMonth) + return getComponent(.Month) } } @@ -190,7 +190,7 @@ public extension NSDate { */ public var weekday : Int { get { - return getComponent(.CalendarUnitWeekday) + return getComponent(.Weekday) } } @@ -199,7 +199,7 @@ public extension NSDate { */ public var weekMonth : Int { get { - return getComponent(.CalendarUnitWeekOfMonth) + return getComponent(.WeekOfMonth) } } @@ -209,7 +209,7 @@ public extension NSDate { */ public var days : Int { get { - return getComponent(.CalendarUnitDay) + return getComponent(.Day) } } @@ -219,7 +219,7 @@ public extension NSDate { public var hours : Int { get { - return getComponent(.CalendarUnitHour) + return getComponent(.Hour) } } @@ -228,7 +228,7 @@ public extension NSDate { */ public var minutes : Int { get { - return getComponent(.CalendarUnitMinute) + return getComponent(.Minute) } } @@ -237,15 +237,15 @@ public extension NSDate { */ public var seconds : Int { get { - return getComponent(.CalendarUnitSecond) + return getComponent(.Second) } } /** Returns the value of the NSDate component - :param: component NSCalendarUnit - :returns: the value of the component + - parameter component: NSCalendarUnit + - returns: the value of the component */ public func getComponent (component : NSCalendarUnit) -> Int { @@ -303,9 +303,6 @@ func -(date: NSDate, otherDate: NSDate) -> NSTimeInterval { return date.timeIntervalSinceDate(otherDate) } -extension NSDate: Equatable { -} - public func ==(lhs: NSDate, rhs: NSDate) -> Bool { return lhs.compare(rhs) == NSComparisonResult.OrderedSame } diff --git a/ExSwift/Range.swift b/ExSwift/Range.swift index 051368d..af4d568 100644 --- a/ExSwift/Range.swift +++ b/ExSwift/Range.swift @@ -13,7 +13,7 @@ internal extension Range { /** For each element in the range invokes function. - :param: function Function to call + - parameter function: Function to call */ func times (function: () -> ()) { each { (current: T) -> () in @@ -24,7 +24,7 @@ internal extension Range { /** For each element in the range invokes function passing the element as argument. - :param: function Function to invoke + - parameter function: Function to invoke */ func times (function: (T) -> ()) { each (function) @@ -33,7 +33,7 @@ internal extension Range { /** For each element in the range invokes function passing the element as argument. - :param: function Function to invoke + - parameter function: Function to invoke */ func each (function: (T) -> ()) { for i in self { @@ -44,7 +44,7 @@ internal extension Range { /** Returns each element of the range in an array - :returns: Each element of the range in an array + - returns: Each element of the range in an array */ func toArray () -> [T] { var result: [T] = [] @@ -57,13 +57,13 @@ internal extension Range { /** Range of Int with random bounds between from and to (inclusive). - :param: from Lower bound - :param: to Upper bound - :returns: Random range + - parameter from: Lower bound + - parameter to: Upper bound + - returns: Random range */ static func random (from: Int, to: Int) -> Range { - let lowerBound = Int.random(min: from, max: to) - let upperBound = Int.random(min: lowerBound, max: to) + let lowerBound = Int.random(from, max: to) + let upperBound = Int.random(lowerBound, max: to) return lowerBound...upperBound } diff --git a/ExSwift/Sequence.swift b/ExSwift/Sequence.swift index 6aa19b3..1b2c043 100644 --- a/ExSwift/Sequence.swift +++ b/ExSwift/Sequence.swift @@ -8,26 +8,26 @@ import Foundation -internal extension SequenceOf { +internal extension AnySequence { /** First element of the sequence. - :returns: First element of the sequence if present + - returns: First element of the sequence if present */ var first: T? { - var generator = self.generate() + let generator = self.generate() return generator.next() } /** Checks if call returns true for any element of self. - :param: call Function to call for each element - :returns: True if call returns true for any element of self + - parameter call: Function to call for each element + - returns: True if call returns true for any element of self */ func any (call: (T) -> Bool) -> Bool { - var generator = self.generate() + let generator = self.generate() while let nextItem = generator.next() { if call(nextItem) { return true @@ -39,11 +39,11 @@ internal extension SequenceOf { /** Object at the specified index if exists. - :param: index - :returns: Object at index in sequence, nil if index is out of bounds + - parameter index: + - returns: Object at index in sequence, nil if index is out of bounds */ func get (index: Int) -> T? { - var generator = self.generate() + let generator = self.generate() for _ in 0..<(index - 1) { generator.next() } @@ -53,18 +53,18 @@ internal extension SequenceOf { /** Objects in the specified range. - :param: range - :returns: Subsequence in range + - parameter range: + - returns: Subsequence in range */ - func get (range: Range) -> SequenceOf { + func get (range: Range) -> AnySequence { return self.skip(range.startIndex).take(range.endIndex - range.startIndex) } /** Index of the first occurrence of item, if found. - :param: item The item to search for - :returns: Index of the matched item or nil + - parameter item: The item to search for + - returns: Index of the matched item or nil */ func indexOf (item: U) -> Int? { var index = 0 @@ -82,34 +82,34 @@ internal extension SequenceOf { /** Subsequence from n to the end of the sequence. - :param: n Number of elements to skip - :returns: Sequence from n to the end + - parameter n: Number of elements to skip + - returns: Sequence from n to the end */ - func skip (n: Int) -> SequenceOf { - var generator = self.generate() + func skip (n: Int) -> AnySequence { + let generator = self.generate() for _ in 0.. Bool) -> SequenceOf { - return SequenceOf(lazy(self).filter(include)) + func filter(include: (T) -> Bool) -> AnySequence { + return AnySequence(lazy(self).filter(include)) } /** Opposite of filter. - :param: exclude Function invoked to test elements for exlcusion from the sequence - :returns: Filtered sequence + - parameter exclude: Function invoked to test elements for exlcusion from the sequence + - returns: Filtered sequence */ - func reject (exclude: (T -> Bool)) -> SequenceOf { + func reject (exclude: (T -> Bool)) -> AnySequence { return self.filter { return !exclude($0) } @@ -118,34 +118,34 @@ internal extension SequenceOf { /** Skips the elements in the sequence up until the condition returns false. - :param: condition A function which returns a boolean if an element satisfies a given condition or not - :returns: Elements of the sequence starting with the element which does not meet the condition + - parameter condition: A function which returns a boolean if an element satisfies a given condition or not + - returns: Elements of the sequence starting with the element which does not meet the condition */ - func skipWhile(condition:(T) -> Bool) -> SequenceOf { - var generator = self.generate() - var checkingGenerator = self.generate() + func skipWhile(condition:(T) -> Bool) -> AnySequence { + let generator = self.generate() + let checkingGenerator = self.generate() var keepSkipping = true while keepSkipping { - var nextItem = checkingGenerator.next() + let nextItem = checkingGenerator.next() keepSkipping = nextItem != nil ? condition(nextItem!) : false if keepSkipping { generator.next() } } - return SequenceOf(generator) + return AnySequence(generator) } /** Checks if self contains the item object. - :param: item The item to search for - :returns: true if self contains item + - parameter item: The item to search for + - returns: true if self contains item */ func contains (item: T) -> Bool { - var generator = self.generate() + let generator = self.generate() while let nextItem = generator.next() { if nextItem as! T == item { return true @@ -157,27 +157,27 @@ internal extension SequenceOf { /** Returns the first n elements from self. - :param: n Number of elements to take - :returns: First n elements + - parameter n: Number of elements to take + - returns: First n elements */ - func take (n: Int) -> SequenceOf { - return SequenceOf(TakeSequence(self, n)) + func take (n: Int) -> AnySequence { + return AnySequence(TakeSequence(self, n)) } /** Returns the elements of the sequence up until an element does not meet the condition. - :param: condition A function which returns a boolean if an element satisfies a given condition or not. - :returns: Elements of the sequence up until an element does not meet the condition + - parameter condition: A function which returns a boolean if an element satisfies a given condition or not. + - returns: Elements of the sequence up until an element does not meet the condition */ - func takeWhile (condition:(T?) -> Bool) -> SequenceOf { - return SequenceOf(TakeWhileSequence(self, condition)) + func takeWhile (condition:(T?) -> Bool) -> AnySequence { + return AnySequence(TakeWhileSequence(self, condition)) } /** Returns each element of the sequence in an array - :returns: Each element of the sequence in an array + - returns: Each element of the sequence in an array */ func toArray () -> [T] { var result: [T] = [] @@ -200,10 +200,10 @@ public struct TakeSequence: SequenceType { self.n = n } - public func generate() -> GeneratorOf { + public func generate() -> AnyGenerator { var count = 0 var generator = self.sequence.generate() - return GeneratorOf { + return anyGenerator { count++ if count > self.n { return nil @@ -226,10 +226,10 @@ public struct TakeWhileSequence: SequenceType { self.condition = condition } - public func generate() -> GeneratorOf { + public func generate() -> AnyGenerator { var generator = self.sequence.generate() var endConditionMet = false - return GeneratorOf { + return anyGenerator { let next: S.Generator.Element? = generator.next() if !endConditionMet { endConditionMet = !self.condition(next) diff --git a/ExSwift/String.swift b/ExSwift/String.swift index 95ff794..38bea6b 100644 --- a/ExSwift/String.swift +++ b/ExSwift/String.swift @@ -13,7 +13,7 @@ public extension String { /** String length */ - var length: Int { return count(self) } + var length: Int { return self.characters.count } /** self.capitalizedString shorthand @@ -23,8 +23,8 @@ public extension String { /** Returns the substring in the given range - :param: range - :returns: Substring in range + - parameter range: + - returns: Substring in range */ subscript (range: Range) -> String? { if range.startIndex < 0 || range.endIndex > self.length { @@ -40,10 +40,10 @@ public extension String { Equivalent to at. Takes a list of indexes and returns an Array containing the elements at the given indexes in self. - :param: firstIndex - :param: secondIndex - :param: restOfIndexes - :returns: Charaters at the specified indexes (converted to String) + - parameter firstIndex: + - parameter secondIndex: + - parameter restOfIndexes: + - returns: Charaters at the specified indexes (converted to String) */ subscript (firstIndex: Int, secondIndex: Int, restOfIndexes: Int...) -> [String] { return at([firstIndex, secondIndex] + restOfIndexes) @@ -53,11 +53,11 @@ public extension String { Gets the character at the specified index as String. If index is negative it is assumed to be relative to the end of the String. - :param: index Position of the character to get - :returns: Character as String or nil if the index is out of bounds + - parameter index: Position of the character to get + - returns: Character as String or nil if the index is out of bounds */ subscript (index: Int) -> String? { - if let char = Array(self).get(index) { + if let char = Array(self.characters).get(index) { return String(char) } @@ -67,8 +67,8 @@ public extension String { /** Takes a list of indexes and returns an Array containing the elements at the given indexes in self. - :param: indexes Positions of the elements to get - :returns: Array of characters (as String) + - parameter indexes: Positions of the elements to get + - returns: Array of characters (as String) */ func at (indexes: Int...) -> [String] { return indexes.map { self[$0]! } @@ -77,8 +77,8 @@ public extension String { /** Takes a list of indexes and returns an Array containing the elements at the given indexes in self. - :param: indexes Positions of the elements to get - :returns: Array of characters (as String) + - parameter indexes: Positions of the elements to get + - returns: Array of characters (as String) */ func at (indexes: [Int]) -> [String] { return indexes.map { self[$0]! } @@ -87,43 +87,44 @@ public extension String { /** Returns an array of strings, each of which is a substring of self formed by splitting it on separator. - :param: separator Character used to split the string - :returns: Array of substrings + - parameter separator: Character used to split the string + - returns: Array of substrings */ func explode (separator: Character) -> [String] { - return split(self, isSeparator: { (element: Character) -> Bool in + return split(self.characters, isSeparator: { (element: Character) -> Bool in return element == separator - }) + }).map { String($0) } } /** Finds any match in self for pattern. - :param: pattern Pattern to match - :param: ignoreCase true for case insensitive matching - :returns: Matches found (as [NSTextCheckingResult]) + - parameter pattern: Pattern to match + - parameter ignoreCase: true for case insensitive matching + - returns: Matches found (as [NSTextCheckingResult]) */ - func matches (pattern: String, ignoreCase: Bool = false) -> [NSTextCheckingResult]? { + func matches (pattern: String, ignoreCase: Bool = false) throws -> [NSTextCheckingResult]? { - if let regex = ExSwift.regex(pattern, ignoreCase: ignoreCase) { + if let regex = try ExSwift.regex(pattern, ignoreCase: ignoreCase) { // Using map to prevent a possible bug in the compiler - return regex.matchesInString(self, options: nil, range: NSMakeRange(0, length)).map { $0 as! NSTextCheckingResult } + return regex.matchesInString(self, options: [], range: NSMakeRange(0, length)).map { $0 as NSTextCheckingResult } } return nil + } /** Check is string with this pattern included in string - :param: pattern Pattern to match - :param: ignoreCase true for case insensitive matching - :returns: true if contains match, otherwise false + - parameter pattern: Pattern to match + - parameter ignoreCase: true for case insensitive matching + - returns: true if contains match, otherwise false */ - func containsMatch (pattern: String, ignoreCase: Bool = false) -> Bool? { - if let regex = ExSwift.regex(pattern, ignoreCase: ignoreCase) { - let range = NSMakeRange(0, count(self)) - return regex.firstMatchInString(self, options: .allZeros, range: range) != nil + func containsMatch (pattern: String, ignoreCase: Bool = false) throws -> Bool? { + if let regex = try ExSwift.regex(pattern, ignoreCase: ignoreCase) { + let range = NSMakeRange(0, self.characters.count) + return regex.firstMatchInString(self, options: [], range: range) != nil } return nil @@ -132,15 +133,15 @@ public extension String { /** Replace all pattern matches with another string - :param: pattern Pattern to match - :param: replacementString string to replace matches - :param: ignoreCase true for case insensitive matching - :returns: true if contains match, otherwise false + - parameter pattern: Pattern to match + - parameter replacementString: string to replace matches + - parameter ignoreCase: true for case insensitive matching + - returns: true if contains match, otherwise false */ - func replaceMatches (pattern: String, withString replacementString: String, ignoreCase: Bool = false) -> String? { - if let regex = ExSwift.regex(pattern, ignoreCase: ignoreCase) { - let range = NSMakeRange(0, count(self)) - return regex.stringByReplacingMatchesInString(self, options: .allZeros, range: range, withTemplate: replacementString) + func replaceMatches (pattern: String, withString replacementString: String, ignoreCase: Bool = false) throws -> String? { + if let regex = try ExSwift.regex(pattern, ignoreCase: ignoreCase) { + let range = NSMakeRange(0, self.characters.count) + return regex.stringByReplacingMatchesInString(self, options: [], range: range, withTemplate: replacementString) } return nil @@ -149,11 +150,11 @@ public extension String { /** Inserts a substring at the given index in self. - :param: index Where the new string is inserted - :param: string String to insert - :returns: String formed from self inserting string at index + - parameter index: Where the new string is inserted + - parameter string: String to insert + - returns: String formed from self inserting string at index */ - func insert (var index: Int, _ string: String) -> String { + func insert (index: Int, _ string: String) -> String { // Edge cases, prepend and append if index > length { return self + string @@ -167,7 +168,7 @@ public extension String { /** Strips the specified characters from the beginning of self. - :returns: Stripped string + - returns: Stripped string */ func trimmedLeft (characterSet set: NSCharacterSet = NSCharacterSet.whitespaceAndNewlineCharacterSet()) -> String { if let range = rangeOfCharacterFromSet(set.invertedSet) { @@ -177,14 +178,14 @@ public extension String { return "" } - @availability(*, unavailable, message="use 'trimmedLeft' instead") func ltrimmed (set: NSCharacterSet = NSCharacterSet.whitespaceAndNewlineCharacterSet()) -> String { + @available(*, unavailable, message="use 'trimmedLeft' instead") func ltrimmed (set: NSCharacterSet = NSCharacterSet.whitespaceAndNewlineCharacterSet()) -> String { return trimmedLeft(characterSet: set) } /** Strips the specified characters from the end of self. - :returns: Stripped string + - returns: Stripped string */ func trimmedRight (characterSet set: NSCharacterSet = NSCharacterSet.whitespaceAndNewlineCharacterSet()) -> String { if let range = rangeOfCharacterFromSet(set.invertedSet, options: NSStringCompareOptions.BackwardsSearch) { @@ -194,14 +195,14 @@ public extension String { return "" } - @availability(*, unavailable, message="use 'trimmedRight' instead") func rtrimmed (set: NSCharacterSet = NSCharacterSet.whitespaceAndNewlineCharacterSet()) -> String { + @available(*, unavailable, message="use 'trimmedRight' instead") func rtrimmed (set: NSCharacterSet = NSCharacterSet.whitespaceAndNewlineCharacterSet()) -> String { return trimmedRight(characterSet: set) } /** Strips whitespaces from both the beginning and the end of self. - :returns: Stripped string + - returns: Stripped string */ func trimmed () -> String { return trimmedLeft().trimmedRight() @@ -210,9 +211,9 @@ public extension String { /** Costructs a string using random chars from a given set. - :param: length String length. If < 1, it's randomly selected in the range 0..16 - :param: charset Chars to use in the random string - :returns: Random string + - parameter length: String length. If < 1, it's randomly selected in the range 0..16 + - parameter charset: Chars to use in the random string + - returns: Random string */ static func random (var length len: Int = 0, charset: String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") -> String { @@ -224,7 +225,7 @@ public extension String { let max = charset.length - 1 len.times { - result += charset[Int.random(min: 0, max: max)]! + result += charset[Int.random(0, max: max)]! } return result @@ -235,7 +236,7 @@ public extension String { /** Parses a string containing a double numerical value into an optional double if the string is a well formed number. - :returns: A double parsed from the string or nil if it cannot be parsed. + - returns: A double parsed from the string or nil if it cannot be parsed. */ func toDouble() -> Double? { @@ -253,7 +254,7 @@ public extension String { /** Parses a string containing a float numerical value into an optional float if the string is a well formed number. - :returns: A float parsed from the string or nil if it cannot be parsed. + - returns: A float parsed from the string or nil if it cannot be parsed. */ func toFloat() -> Float? { @@ -271,10 +272,10 @@ public extension String { /** Parses a string containing a non-negative integer value into an optional UInt if the string is a well formed number. - :returns: A UInt parsed from the string or nil if it cannot be parsed. + - returns: A UInt parsed from the string or nil if it cannot be parsed. */ func toUInt() -> UInt? { - if let val = self.trimmed().toInt() { + if let val = Int(self.trimmed()) { if val < 0 { return nil } @@ -288,7 +289,7 @@ public extension String { /** Parses a string containing a boolean value (true or false) into an optional Bool if the string is a well formed. - :returns: A Bool parsed from the string or nil if it cannot be parsed as a boolean. + - returns: A Bool parsed from the string or nil if it cannot be parsed as a boolean. */ func toBool() -> Bool? { let text = self.trimmed().lowercaseString @@ -303,11 +304,11 @@ public extension String { Parses a string containing a date into an optional NSDate if the string is a well formed. The default format is yyyy-MM-dd, but can be overriden. - :returns: A NSDate parsed from the string or nil if it cannot be parsed as a date. + - returns: A NSDate parsed from the string or nil if it cannot be parsed as a date. */ func toDate(format : String? = "yyyy-MM-dd") -> NSDate? { let text = self.trimmed().lowercaseString - var dateFmt = NSDateFormatter() + let dateFmt = NSDateFormatter() dateFmt.timeZone = NSTimeZone.defaultTimeZone() if let fmt = format { dateFmt.dateFormat = fmt @@ -319,10 +320,10 @@ public extension String { Parses a string containing a date and time into an optional NSDate if the string is a well formed. The default format is yyyy-MM-dd hh-mm-ss, but can be overriden. - :returns: A NSDate parsed from the string or nil if it cannot be parsed as a date. + - returns: A NSDate parsed from the string or nil if it cannot be parsed as a date. */ func toDateTime(format : String? = "yyyy-MM-dd hh-mm-ss") -> NSDate? { - return toDate(format: format) + return toDate(format) } } @@ -343,10 +344,10 @@ public func * (first: String, n: Int) -> String { } // Pattern matching using a regular expression -public func =~ (string: String, pattern: String) -> Bool { +public func =~ (string: String, pattern: String) throws -> Bool { - let regex = ExSwift.regex(pattern, ignoreCase: false)! - let matches = regex.numberOfMatchesInString(string, options: nil, range: NSMakeRange(0, string.length)) + let regex = try ExSwift.regex(pattern, ignoreCase: false)! + let matches = regex.numberOfMatchesInString(string, options: [], range: NSMakeRange(0, string.length)) return matches > 0 @@ -355,16 +356,16 @@ public func =~ (string: String, pattern: String) -> Bool { // Pattern matching using a regular expression public func =~ (string: String, regex: NSRegularExpression) -> Bool { - let matches = regex.numberOfMatchesInString(string, options: nil, range: NSMakeRange(0, string.length)) + let matches = regex.numberOfMatchesInString(string, options: [], range: NSMakeRange(0, string.length)) return matches > 0 } // This version also allowes to specify case sentitivity -public func =~ (string: String, options: (pattern: String, ignoreCase: Bool)) -> Bool { +public func =~ (string: String, options: (pattern: String, ignoreCase: Bool)) throws -> Bool { - if let matches = ExSwift.regex(options.pattern, ignoreCase: options.ignoreCase)?.numberOfMatchesInString(string, options: nil, range: NSMakeRange(0, string.length)) { + if let matches = try ExSwift.regex(options.pattern, ignoreCase: options.ignoreCase)?.numberOfMatchesInString(string, options: [], range: NSMakeRange(0, string.length)) { return matches > 0 } @@ -373,31 +374,61 @@ public func =~ (string: String, options: (pattern: String, ignoreCase: Bool)) -> } // Match against all the alements in an array of String -public func =~ (strings: [String], pattern: String) -> Bool { +public func =~ (strings: [String], pattern: String) throws -> Bool { - let regex = ExSwift.regex(pattern, ignoreCase: false)! + let regex = try ExSwift.regex(pattern, ignoreCase: false)! return strings.all { $0 =~ regex } } -public func =~ (strings: [String], options: (pattern: String, ignoreCase: Bool)) -> Bool { +public func =~ (strings: [String], options: (pattern: String, ignoreCase: Bool)) throws -> Bool { - return strings.all { $0 =~ options } + var lastError: ErrorType? + let result = strings.all { + do { + return try $0 =~ options + } catch let error { + lastError = error + return false + } + } + + if let error = lastError { + throw error + } + + return result + } // Match against any element in an array of String -public func |~ (strings: [String], pattern: String) -> Bool { +public func |~ (strings: [String], pattern: String) throws -> Bool { - let regex = ExSwift.regex(pattern, ignoreCase: false)! + let regex = try ExSwift.regex(pattern, ignoreCase: false)! return strings.any { $0 =~ regex } } -public func |~ (strings: [String], options: (pattern: String, ignoreCase: Bool)) -> Bool { +public func |~ (strings: [String], options: (pattern: String, ignoreCase: Bool)) throws -> Bool { - return strings.any { $0 =~ options } + var lastError: ErrorType? + + let result = strings.any { + do { + return try $0 =~ options + } catch let error { + lastError = error + return false + } + } + + if let error = lastError { + throw error + } + + return result } diff --git a/ExSwiftTests/ArrayExtensionsTests.swift b/ExSwiftTests/ArrayExtensionsTests.swift index 8a50b22..d1cc9ae 100644 --- a/ExSwiftTests/ArrayExtensionsTests.swift +++ b/ExSwiftTests/ArrayExtensionsTests.swift @@ -30,7 +30,7 @@ class ArrayExtensionsSpec: QuickSpec { it("in bounds") { - for i in enumerate(self.intArray) { + for i in self.intArray.enumerate() { expect(self.intArray.get(i.index)) == (i.element) } @@ -370,18 +370,19 @@ class ArrayExtensionsSpec: QuickSpec { it("method") { - expect(self.intArray.difference([3, 4])) == [1, 2, 5] - + // Xcode 7.0 b1: diff_1 and diff_2 are needed in order to prevent crashes + let diff_1 = [3, 4] + expect(self.intArray.difference(diff_1)) == [1, 2, 5] expect(self.intArray.difference([3], [4])) == [1, 2, 5] - expect(self.intArray.difference([])) == self.intArray + let diff_2: [Int] = [] + expect(self.intArray.difference(diff_2)) == self.intArray } it("operator") { expect(self.intArray - [3, 4]) == [1, 2, 5] - expect(self.intArray - [3] - [4]) == [1, 2, 5] expect(self.intArray - []) == self.intArray @@ -397,7 +398,9 @@ class ArrayExtensionsSpec: QuickSpec { it("method") { - expect(self.intArray.intersection([])) == [] + // Xcode 7.0 b1: int_1 is needed in order to prevent crashes + let int_1: [Int] = [] + expect(self.intArray.intersection(int_1)) == [] expect(self.intArray.intersection([1])) == [1] @@ -414,7 +417,7 @@ class ArrayExtensionsSpec: QuickSpec { expect(self.intArray & [1, 2] & [1, 2] & [1, 2, 3]) == [1, 2] } - + } /** @@ -424,7 +427,9 @@ class ArrayExtensionsSpec: QuickSpec { it("method") { - expect(self.intArray.union([])) == self.intArray + // Xcode 7.0 b1: uni_1 is needed in order to prevent crashes + let uni_1: [Int] = [] + expect(self.intArray.union(uni_1)) == self.intArray expect(self.intArray.union([1])) == self.intArray @@ -594,7 +599,7 @@ class ArrayExtensionsSpec: QuickSpec { } - for i in enumerate(self.intArray) { + for i in self.intArray.enumerate() { expect(dictionary["Number \(i.element)"]) == i.element @@ -623,27 +628,6 @@ class ArrayExtensionsSpec: QuickSpec { } - /** - * Array.implode - */ - describe("implode") { - - it("method") { - - expect(self.stringArray.implode("")) == "ABCDEF" - expect(self.stringArray.implode("*")) == "A*B*C*D*E*F" - - } - - it("operator") { - - expect(self.stringArray * "") == "ABCDEF" - expect(self.stringArray * "*") == "A*B*C*D*E*F" - - } - - } - /** * Array.flatten */ @@ -861,7 +845,7 @@ class ArrayExtensionsSpec: QuickSpec { */ it("shuffled") { - var array = self.intArray + let array = self.intArray self.intArray.shuffle() @@ -903,7 +887,7 @@ class ArrayExtensionsSpec: QuickSpec { var sum = 0 - self.intArray.cycle(n: 2) { + self.intArray.cycle(2) { sum += $0 } @@ -911,13 +895,13 @@ class ArrayExtensionsSpec: QuickSpec { sum = 0 - self.intArray.cycle(n: 0) { + self.intArray.cycle(0) { sum += $0 } expect(sum) == 0 - self.intArray.cycle(n: -1) { + self.intArray.cycle(-1) { sum += $0 } @@ -980,7 +964,7 @@ class ArrayExtensionsSpec: QuickSpec { */ it("repeatedCombination") { - var array = [1, 2, 3] + let array = [1, 2, 3] expect(array.repeatedCombination(-1)) == [] @@ -1025,8 +1009,8 @@ class ArrayExtensionsSpec: QuickSpec { } } - var jagged: [[String]] = [["a", "b", "c"], ["d", "e"], ["f", "g", "h"]] - var jaggedTransposition = [].transposition(jagged) + let jagged: [[String]] = [["a", "b", "c"], ["d", "e"], ["f", "g", "h"]] + let jaggedTransposition = [].transposition(jagged) expect(jaggedTransposition) == [["a", "d", "f"], ["b", "e", "g"], ["c", "h"]] @@ -1038,7 +1022,7 @@ class ArrayExtensionsSpec: QuickSpec { it("permutation") { 1.upTo(self.intArray.count) { i in - var permutations: [[Int]] = self.intArray.permutation(i) + let permutations: [[Int]] = self.intArray.permutation(i) var factorial = 1 for j in 1...i { @@ -1047,8 +1031,8 @@ class ArrayExtensionsSpec: QuickSpec { expect(permutations.count) == self.intArray.combination(i).count * factorial - var mappedPermutations: [Int] = permutations.map({ (i: [Int]) -> [Int] in i.unique()}).flatten() - var flattenedPermutations: [Int] = permutations.flatten() + let mappedPermutations: [Int] = permutations.map({ (i: [Int]) -> [Int] in i.unique()}).flatten() + let flattenedPermutations: [Int] = permutations.flatten() expect(mappedPermutations) == flattenedPermutations expect(permutations.flatten().all({$0 >= 1 && $0 <= 5})).to(beTrue()) @@ -1066,7 +1050,7 @@ class ArrayExtensionsSpec: QuickSpec { */ it("repeatedPermutation") { - var shortArray = [1, 2] + let shortArray = [1, 2] expect(shortArray.repeatedPermutation(0)) == [] expect(shortArray.repeatedPermutation(1)) == [[1], [2]] diff --git a/ExSwiftTests/ExSwiftTests.swift b/ExSwiftTests/ExSwiftTests.swift index b92ab05..3bad07e 100644 --- a/ExSwiftTests/ExSwiftTests.swift +++ b/ExSwiftTests/ExSwiftTests.swift @@ -68,7 +68,17 @@ class ExSwiftSpec: QuickSpec { it("bind") { let concat = { (params: String...) -> String in - return params.implode(" ")! + guard params.count > 0 else { + return "" + } + + var result: String = params.first! + + for param in params.skip(1) { + result += " \(param)" + } + + return result } let helloWorld = ExSwift.bind(concat, "Hello", "World") diff --git a/ExSwiftTests/Info.plist b/ExSwiftTests/Info.plist index b6ebc4a..6d32c15 100644 --- a/ExSwiftTests/Info.plist +++ b/ExSwiftTests/Info.plist @@ -7,7 +7,7 @@ CFBundleExecutable ${EXECUTABLE_NAME} CFBundleIdentifier - co.pNre.${PRODUCT_NAME:rfc1034identifier} + $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName diff --git a/ExSwiftTests/IntExtensionsTests.swift b/ExSwiftTests/IntExtensionsTests.swift index 09dc176..397a56b 100644 --- a/ExSwiftTests/IntExtensionsTests.swift +++ b/ExSwiftTests/IntExtensionsTests.swift @@ -73,7 +73,7 @@ class IntExtensionsSpec: QuickSpec { it("random") { var indexes = [Int]() - 10.times { indexes.append(Int.random(min: 5, max: 25)) } + 10.times { indexes.append(Int.random(5, max: 25)) } expect(indexes).to(allPass { $0 >= 5 && $0 <= 25 }) diff --git a/ExSwiftTests/NSDateExtensionsTests.swift b/ExSwiftTests/NSDateExtensionsTests.swift index 5f027d2..3ec75cd 100644 --- a/ExSwiftTests/NSDateExtensionsTests.swift +++ b/ExSwiftTests/NSDateExtensionsTests.swift @@ -149,8 +149,8 @@ class NSDateExtensionsSpec: QuickSpec { let date = NSDate() - var futureDate = date.addSeconds(42) - var pastDate = date.addSeconds(-42) + let futureDate = date.addSeconds(42) + let pastDate = date.addSeconds(-42) expect(futureDate.isAfter(date)).to(beTrue()) expect(date.isAfter(date)).to(beFalse()) @@ -162,8 +162,8 @@ class NSDateExtensionsSpec: QuickSpec { let date = NSDate() - var futureDate = date.addSeconds(42) - var pastDate = date.addSeconds(-42) + let futureDate = date.addSeconds(42) + let pastDate = date.addSeconds(-42) expect(futureDate.isBefore(date)).to(beFalse()) expect(date.isBefore(date)).to(beFalse()) @@ -201,14 +201,14 @@ class NSDateExtensionsSpec: QuickSpec { let expected = [fifthDate, secondDate, firstDate, thirdDate, fourthDate] let expectedReverded = expected.reverse() - for i in 0 ... 42 { + for _ in 0 ... 42 { dates.shuffle() - dates.sort( { $0 > $1 } ) + dates.sortInPlace( { $0 > $1 } ) expect(dates) == expected - dates.sort( { $0 < $1 } ) - expect(dates) == expectedReverded + dates.sortInPlace( { $0 < $1 } ) + expect(dates) == Array(expectedReverded) } } diff --git a/ExSwiftTests/SequenceExtensionsTests.swift b/ExSwiftTests/SequenceExtensionsTests.swift index 74829ae..bd6111c 100644 --- a/ExSwiftTests/SequenceExtensionsTests.swift +++ b/ExSwiftTests/SequenceExtensionsTests.swift @@ -19,61 +19,61 @@ class SequenceExtensionsSpec: QuickSpec { it("first") { - expect(SequenceOf(self.sequence).first) == 1 + expect(AnySequence(self.sequence).first) == 1 - expect(SequenceOf(self.emptySequence).first).to(beNil()) + expect(AnySequence(self.emptySequence).first).to(beNil()) } it("contains") { - expect(SequenceOf(self.sequence).contains(1)).to(beTrue()) - expect(SequenceOf(self.sequence).contains(56)).to(beFalse()) + expect(AnySequence(self.sequence).contains(1)).to(beTrue()) + expect(AnySequence(self.sequence).contains(56)).to(beFalse()) } it("indexOf") { - expect(SequenceOf(self.sequence).indexOf(2)) == 1 - expect(SequenceOf(self.sequence).indexOf(56)).to(beNil()) + expect(AnySequence(self.sequence).indexOf(2)) == 1 + expect(AnySequence(self.sequence).indexOf(56)).to(beNil()) } it("skip") { - expect(Array(SequenceOf(self.sequence).skip(0))) == Array(SequenceOf(self.sequence)) + expect(Array(AnySequence(self.sequence).skip(0))) == Array(AnySequence(self.sequence)) - expect(Array(SequenceOf(self.sequence).skip(2))) == [3, 4, 5] + expect(Array(AnySequence(self.sequence).skip(2))) == [3, 4, 5] - expect(Array(SequenceOf(self.sequence).skip(8))) == [] + expect(Array(AnySequence(self.sequence).skip(8))) == [] } it("skipWhile") { - expect(Array(SequenceOf(self.sequence).skipWhile { $0 < 3 })) == [3, 4, 5] + expect(Array(AnySequence(self.sequence).skipWhile { $0 < 3 })) == [3, 4, 5] - expect(Array(SequenceOf(self.sequence).skipWhile { $0 < 20 })) == [] + expect(Array(AnySequence(self.sequence).skipWhile { $0 < 20 })) == [] } it("take") { - expect(Array(SequenceOf(self.sequence).take(0))) == [] + expect(Array(AnySequence(self.sequence).take(0))) == [] - expect(Array(SequenceOf(self.sequence).take(2))) == [1, 2] + expect(Array(AnySequence(self.sequence).take(2))) == [1, 2] - expect(Array(SequenceOf(self.sequence).take(20))) == Array(SequenceOf(self.sequence)) + expect(Array(AnySequence(self.sequence).take(20))) == Array(AnySequence(self.sequence)) } it("takeWhile") { - expect(Array(SequenceOf(self.sequence).takeWhile { $0 != 3 })) == [1, 2] + expect(Array(AnySequence(self.sequence).takeWhile { $0 != 3 })) == [1, 2] - expect(Array(SequenceOf(self.sequence).takeWhile { $0 == 7 })) == [] + expect(Array(AnySequence(self.sequence).takeWhile { $0 == 7 })) == [] - expect(Array(SequenceOf(self.sequence).takeWhile { $0 != 7 })) == [1, 2, 3, 4, 5] + expect(Array(AnySequence(self.sequence).takeWhile { $0 != 7 })) == [1, 2, 3, 4, 5] } @@ -81,18 +81,18 @@ class SequenceExtensionsSpec: QuickSpec { it("index") { - expect(SequenceOf(self.sequence).get(3)) == 3 - expect(SequenceOf(self.sequence).get(22)).to(beNil()) + expect(AnySequence(self.sequence).get(3)) == 3 + expect(AnySequence(self.sequence).get(22)).to(beNil()) } it("range") { - expect(Array(SequenceOf(self.sequence).get(1..<3))) == [2, 3] + expect(Array(AnySequence(self.sequence).get(1..<3))) == [2, 3] - expect(Array(SequenceOf(self.sequence).get(0..<0))) == [] + expect(Array(AnySequence(self.sequence).get(0..<0))) == [] - expect(Array(SequenceOf(self.sequence).get(10..<15))) == [] + expect(Array(AnySequence(self.sequence).get(10..<15))) == [] } @@ -100,37 +100,37 @@ class SequenceExtensionsSpec: QuickSpec { it("any") { - expect(SequenceOf(self.sequence).any { $0 == 1 }).to(beTrue()) + expect(AnySequence(self.sequence).any { $0 == 1 }).to(beTrue()) - expect(SequenceOf(self.sequence).any { $0 == 77 }).to(beFalse()) + expect(AnySequence(self.sequence).any { $0 == 77 }).to(beFalse()) } it("filter") { - var evens = SequenceOf(self.sequence).filter { $0 % 2 == 0 } + let evens = AnySequence(self.sequence).filter { $0 % 2 == 0 } expect(Array(evens)) == [2, 4] - var odds = SequenceOf(self.sequence).filter { $0 % 2 == 1 } + let odds = AnySequence(self.sequence).filter { $0 % 2 == 1 } expect(Array(odds)) == [1, 3, 5] - var all = SequenceOf(self.sequence).filter { $0 < 10 } + let all = AnySequence(self.sequence).filter { $0 < 10 } expect(Array(all)) == [1, 2, 3, 4, 5] - var none = SequenceOf(self.sequence).filter { $0 > 10 } + let none = AnySequence(self.sequence).filter { $0 > 10 } expect(Array(none)) == [] } it("reject") { - var rejected = SequenceOf(self.sequence).reject { $0 == 3 } + var rejected = AnySequence(self.sequence).reject { $0 == 3 } expect(Array(rejected)) == [1, 2, 4, 5] - rejected = SequenceOf(self.sequence).reject { $0 == 1 } + rejected = AnySequence(self.sequence).reject { $0 == 1 } expect(Array(rejected)) == [2, 3, 4, 5] - rejected = SequenceOf(self.sequence).reject { $0 == 10 } + rejected = AnySequence(self.sequence).reject { $0 == 10 } expect(Array(rejected)) == [1, 2, 3, 4, 5] } diff --git a/ExSwiftTests/StringExtensionsTests.swift b/ExSwiftTests/StringExtensionsTests.swift index fbc5be3..b5f72f5 100644 --- a/ExSwiftTests/StringExtensionsTests.swift +++ b/ExSwiftTests/StringExtensionsTests.swift @@ -116,18 +116,18 @@ class StringExtensionsSpec: QuickSpec { let string = "ABcd" - expect(string =~ "^A").to(beTrue()) + expect(try! string =~ "^A").to(beTrue()) - expect(string =~ (pattern: "D$", ignoreCase: true)).to(beTrue()) - expect(string =~ "D$").to(beFalse()) + expect(try! string =~ (pattern: "D$", ignoreCase: true)).to(beTrue()) + expect(try! string =~ "D$").to(beFalse()) // String[] all let strings = [string, string, string] - expect(strings =~ "^A").to(beTrue()) + expect(try! strings =~ "^A").to(beTrue()) - expect(strings =~ (pattern: "D$", ignoreCase: true)).to(beTrue()) - expect(strings =~ "D$").to(beFalse()) + expect(try! strings =~ (pattern: "D$", ignoreCase: true)).to(beTrue()) + expect(try! strings =~ "D$").to(beFalse()) } @@ -136,10 +136,10 @@ class StringExtensionsSpec: QuickSpec { // String[] any let strings = ["ABcd", "ABcd", "ABcd"] - XCTAssertTrue(strings |~ "^A") + XCTAssertTrue(try! strings |~ "^A") - XCTAssertTrue(strings |~ (pattern: "D$", ignoreCase: true)) - XCTAssertFalse(strings |~ "D$") + XCTAssertTrue(try! strings |~ (pattern: "D$", ignoreCase: true)) + XCTAssertFalse(try! strings |~ "D$") } @@ -147,13 +147,13 @@ class StringExtensionsSpec: QuickSpec { let string = "AB[31]" - let matches = string.matches("\\d+")! + let matches = try! string.matches("\\d+")! let range = matches[0].rangeAtIndex(0) let substringRange = range.location..<(range.location + range.length) expect(string[substringRange]) == "31" - expect(string.matches("N")!.isEmpty).to(beTrue()) + expect(try! string.matches("N")!.isEmpty).to(beTrue()) } @@ -165,10 +165,10 @@ class StringExtensionsSpec: QuickSpec { */ describe("containsMatch checks"){ it("match") { - expect("Test string for match".containsMatch("for")).to(beTrue()) + expect(try! "Test string for match".containsMatch("for")).to(beTrue()) } it("not match") { - expect("Test string for match".containsMatch("not for")).to(beFalse()) + expect(try! "Test string for match".containsMatch("not for")).to(beFalse()) } } @@ -177,15 +177,15 @@ class StringExtensionsSpec: QuickSpec { */ describe("ReplaceMatches checks"){ it("find match to replace") { - expect("Test_string".replaceMatches("_.*", withString: "_replace")) == "Test_replace" + expect(try! "Test_string".replaceMatches("_.*", withString: "_replace")) == "Test_replace" } it("find match to replacei with empty string") { - expect("Test 111string 222for333 match".replaceMatches("\\d+", withString: "")) == "Test string for match" + expect(try! "Test 111string 222for333 match".replaceMatches("\\d+", withString: "")) == "Test string for match" } it("not find match to replace") { - expect("Test string for match".replaceMatches("\\d+", withString: "some string")) == "Test string for match" + expect(try! "Test string for match".replaceMatches("\\d+", withString: "some string")) == "Test string for match" } } @@ -298,14 +298,14 @@ class StringExtensionsSpec: QuickSpec { it("toDate") { - var d : NSDate = " 2015-08-19 \t ".toDate()! + let d : NSDate = " 2015-08-19 \t ".toDate()! - var c = NSDateComponents() + let c = NSDateComponents() c.year = 2015 c.month = 8 c.day = 19 - var gregorian = NSCalendar(identifier: NSCalendarIdentifierGregorian)! + let gregorian = NSCalendar(identifier: NSCalendarIdentifierGregorian)! expect(gregorian.dateFromComponents(c)) == d expect("a772.2".toDate()).to(beNil()) @@ -316,9 +316,9 @@ class StringExtensionsSpec: QuickSpec { it("toDateTime") { - var d : NSDate = " 2015-08-19 03:04:34\t ".toDateTime()! + let d : NSDate = " 2015-08-19 03:04:34\t ".toDateTime()! - var c = NSDateComponents() + let c = NSDateComponents() c.year = 2015 c.month = 8 c.day = 19 @@ -326,7 +326,7 @@ class StringExtensionsSpec: QuickSpec { c.minute = 4 c.second = 34 - var gregorian = NSCalendar(identifier: NSCalendarIdentifierGregorian)! + let gregorian = NSCalendar(identifier: NSCalendarIdentifierGregorian)! expect(gregorian.dateFromComponents(c)) == d expect("a772.2".toDateTime()).to(beNil()) diff --git a/Podfile b/Podfile index d9f4bf2..812cbd8 100644 --- a/Podfile +++ b/Podfile @@ -3,8 +3,8 @@ use_frameworks! def import_test_pods - pod 'Quick', '~> 0.3.1' - pod 'Nimble', '~> 0.4.2' + pod 'Quick', :git => 'https://github.com/Quick/Quick', :branch => 'swift-2.0' + pod 'Nimble', :git => 'https://github.com/Quick/Nimble', :branch => 'swift-2.0' end diff --git a/Podfile.lock b/Podfile.lock index 79a06b6..430a66b 100644 --- a/Podfile.lock +++ b/Podfile.lock @@ -1,13 +1,29 @@ PODS: - - Nimble (0.4.2) + - Nimble (1.0.0-rc.1) - Quick (0.3.1) DEPENDENCIES: - - Nimble (~> 0.4.2) - - Quick (~> 0.3.1) + - Nimble (from `https://github.com/Quick/Nimble`, branch `swift-2.0`) + - Quick (from `https://github.com/Quick/Quick`, branch `swift-2.0`) + +EXTERNAL SOURCES: + Nimble: + :branch: swift-2.0 + :git: https://github.com/Quick/Nimble + Quick: + :branch: swift-2.0 + :git: https://github.com/Quick/Quick + +CHECKOUT OPTIONS: + Nimble: + :commit: 3102770b04cb716bc38f28add2feac15dbbbf2ab + :git: https://github.com/Quick/Nimble + Quick: + :commit: a840a9e33a673e20a0225912c85bb314074cc161 + :git: https://github.com/Quick/Quick SPEC CHECKSUMS: - Nimble: 49b7a7da8919f42823d37c6d68cc6d15a7009f32 + Nimble: 23f1dbddf1706172c7d740430858e5dfa93d997a Quick: 824572d3d198d51e52cf4aa722cebf7e59952a35 -COCOAPODS: 0.37.1 +COCOAPODS: 0.37.2 From 123fd55f5f0dea227310b64dd442ea157104acba Mon Sep 17 00:00:00 2001 From: pNre Date: Tue, 9 Jun 2015 21:34:06 +0200 Subject: [PATCH 02/11] Exclude the Swift-2.0 branch from travis-ci builds --- .travis.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.travis.yml b/.travis.yml index e20cbe9..230f9f5 100644 --- a/.travis.yml +++ b/.travis.yml @@ -15,3 +15,7 @@ matrix: xcode_sdk: macosx10.10 - xcode_scheme: ExSwift-Mac xcode_sdk: iphonesimulator8.3 + +branches: + except: + - Swift-2.0 From 7040447ac05419eae131ecc6c45cef9afb28dc80 Mon Sep 17 00:00:00 2001 From: Andrew Ng Date: Thu, 3 Sep 2015 17:37:02 -0700 Subject: [PATCH 03/11] Swift 2 and Xcode 7 beta 6 fixes --- ExSwift/Array.swift | 142 ++++++++++++++++++++++------------------- ExSwift/ExSwift.swift | 23 ++++--- ExSwift/NSArray.swift | 11 ++-- ExSwift/NSDate.swift | 2 +- ExSwift/Range.swift | 10 +-- ExSwift/Sequence.swift | 30 ++++----- ExSwift/String.swift | 6 +- 7 files changed, 115 insertions(+), 109 deletions(-) diff --git a/ExSwift/Array.swift b/ExSwift/Array.swift index 5bdbeac..c4c98d5 100644 --- a/ExSwift/Array.swift +++ b/ExSwift/Array.swift @@ -18,8 +18,8 @@ internal extension Array { - parameter items: Items to search for - returns: true if self contains all the items */ - func contains (items: T...) -> Bool { - return items.all { (item: T) -> Bool in self.indexOf(item) >= 0 } + func contains (items: Element...) -> Bool { + return items.all { (item: Element) -> Bool in self.indexOf(item) >= 0 } } /** @@ -28,12 +28,12 @@ internal extension Array { - parameter values: Arrays to subtract - returns: Difference of self and the input arrays */ - func difference (values: [T]...) -> [T] { + func difference (values: [Element]...) -> [Element] { - var result = [T]() + var result = [Element]() elements: for e in self { - if let element = e as? T { + if let element = e as? Element { for value in values { // if a value is in both self and one of the values arrays // jump to the next iteration of the outer loop @@ -131,7 +131,7 @@ internal extension Array { - parameter item: The item to search for - returns: Matched item or nil */ - func find (item: U) -> T? { + func find (item: U) -> Element? { if let index: Int = indexOf(item) { return self[index] } @@ -173,7 +173,7 @@ internal extension Array { */ func lastIndexOf (item: U) -> Int? { if item is Element { - for (index, value) in lazy(self).reverse().enumerate() { + for (index, value) in self.reverse().enumerate() { if value as! U == item { return count - 1 - index } @@ -205,7 +205,7 @@ internal extension Array { */ func get (range: Range) -> Array { - return self[rangeAsArray: range] + return Array(self[range]) } @@ -222,15 +222,16 @@ internal extension Array { // Gets the longest sequence let max = arrays.map { (element: Any) -> Int in - return reflect(element).count + return Int(Mirror(reflecting: element).children.count) }.max() as Int for i in 0.. Any? in - let (_, mirror) = reflect(element)[i] - return mirror.value + // let (_, mirror) = reflect(element)[i] + // return mirror.value + return Mirror(reflecting: element).children }) } @@ -258,8 +259,8 @@ internal extension Array { if n < 1 { n = 0 } // Allow 0 if user wants [[],[],[]] for some reason. if n > count { return [[]] } - for i in stride(from: 0, through: count - n, by: step!) { - result += [self[i..<(i + n)]] + for i in 0.stride(through: count - n, by: step!) { + result += [Array(self[i..<(i + n)])] } return result @@ -293,14 +294,14 @@ internal extension Array { n = 0 } - for i in stride(from: 0, to: count, by: step!) { + for i in 0.stride(through: count, by: step!) { var end = i + n if end > count { end = count } - - result += [self[i.. (cond: (Element) -> T) -> [Array] { + func partitionBy (cond: (Element) -> Element) -> [Array] { var result = [Array]() - var lastValue: T? = nil + var lastValue: Element? = nil for item in self { - let value = cond(item) + let value = cond(item as! Element) if value == lastValue { let index: Int = result.count - 1 @@ -402,7 +403,7 @@ internal extension Array { } let index = Int.random(max: count - n) - return self[index..<(n + index)] + return Array(self[index..<(n + index)]) } /** @@ -439,7 +440,7 @@ internal extension Array { func maxBy (call: (Element) -> (U)) -> Element? { if let firstValue = self.first { - var maxElement: T = firstValue + var maxElement: Element = firstValue var maxValue: U = call(firstValue) for i in 1.. (call: (Element) -> (U)) -> Element? { if let firstValue = self.first { - var minElement: T = firstValue + var minElement: Element = firstValue var minValue: U = call(firstValue) for i in 1.. Array { - return self[0.. Array { - return self[(count - n).. Array { - return n > count ? [] : self[Int(n).. count ? [] : Array(self[Int(n).. () -> [T] { - var result = [T]() + func unique () -> [Element] { + var result = [Element]() for item in self { - if !result.contains(item as! T) { - result.append(item as! T) + if !result.contains(item as! Element) { + result.append(item as! Element) } } @@ -690,37 +691,37 @@ internal extension Array { - parameter call: The closure to use to determine uniqueness - returns: The set of elements for which call(element) is unique */ - func uniqueBy (call: (Element) -> (T)) -> [Element] { + func uniqueBy (call: (Element) -> (Element)) -> [Element] { var result: [Element] = [] - var uniqueItems: [T] = [] + var uniqueItems: [Element] = [] for item in self { - let callResult: T = call(item) + let callResult: Element = call(item as! Element) if !uniqueItems.contains(callResult) { uniqueItems.append(callResult) - result.append(item) + result.append(item as! Element) } } return result } - + /** Returns all permutations of a given length within an array - parameter length: The length of each permutation - returns: All permutations of a given length within an array */ - func permutation (length: Int) -> [[T]] { + func permutation (length: Int) -> [[Element]] { if length < 0 || length > self.count { return [] } else if length == 0 { return [[]] } else { - var permutations: [[T]] = [] + var permutations: [[Element]] = [] let combinations = combination(length) for combination in combinations { - var endArray: [[T]] = [] + var endArray: [[Element]] = [] var mutableCombination = combination permutations += self.permutationHelper(length, array: &mutableCombination, endArray: &endArray) } @@ -732,7 +733,7 @@ internal extension Array { Recursive helper method where all of the permutation-generating work is done This is Heap's algorithm */ - private func permutationHelper(n: Int, inout array: [T], inout endArray: [[T]]) -> [[T]] { + private func permutationHelper(n: Int, inout array: [Element], inout endArray: [[Element]]) -> [[Element]] { if n == 1 { endArray += [array] } @@ -740,7 +741,7 @@ internal extension Array { permutationHelper(n - 1, array: &array, endArray: &endArray) let j = n % 2 == 0 ? i : 0; //(array[j], array[n - 1]) = (array[n - 1], array[j]) - let temp: T = array[j] + let temp: Element = array[j] array[j] = array[n - 1] array[n - 1] = temp } @@ -878,7 +879,7 @@ internal extension Array { - parameter length: The length of each permutations :returns All of the permutations of this array of a given length, allowing repeats */ - func repeatedPermutation(length: Int) -> [[T]] { + func repeatedPermutation(length: Int) -> [[Element]] { if length < 1 { return [] } @@ -929,9 +930,9 @@ internal extension Array { :return: A transposed version of the array, where the object at array[i][j] goes to array[j][i] */ - func transposition (array: [[T]]) -> [[T]] { // () -> [[U]] { + func transposition (array: [[Element]]) -> [[Element]] { // () -> [[U]] { let maxWidth: Int = array.map({ $0.count }).max() - var transposition = [[T]](count: maxWidth, repeatedValue: []) + var transposition = [[Element]](count: maxWidth, repeatedValue: []) (0.. () { + mutating func fill (object: Element) -> () { (0.. (separator: C) -> C? { + func implode (separator: C) -> C? { if Element.self is C.Type { - return Swift.join(separator, unsafeBitCast(self, [C].self)) + if let joined = unsafeBitCast(self, [C].self).joinWithSeparator(separator) as? C { + return joined + } else { + return nil + } } return nil @@ -1085,15 +1090,18 @@ internal extension Array { */ func flatten () -> [OutType] { var result = [OutType]() - let reflection = reflect(self) - - for i in 0.. Bool) -> [T] { + @available(*, unavailable, message="use 'sort' instead") func sortBy (isOrderedBefore: (Element, Element) -> Bool) -> [Element] { return sort(isOrderedBefore) } @@ -1129,7 +1137,7 @@ internal extension Array { - parameter n: the number of times to cycle through - parameter block: the block to run for each element in each cycle */ - func cycle (n: Int? = nil, block: (T) -> ()) { + func cycle (n: Int? = nil, block: (Element) -> ()) { var cyclesRun = 0 while true { if let n = n { @@ -1154,7 +1162,7 @@ internal extension Array { - parameter block: the block to run each time - returns: the min element, or nil if there are no items for which the block returns true */ - func bSearch (block: (T) -> (Bool)) -> T? { + func bSearch (block: (Element) -> (Bool)) -> Element? { if count == 0 { return nil } @@ -1188,7 +1196,7 @@ internal extension Array { - parameter block: the block to run each time - returns: an item (there could be multiple matches) for which the block returns true */ - func bSearch (block: (T) -> (Int)) -> T? { + /*func bSearch (block: (Element) -> (Int)) -> Element? { let match = bSearch { item in block(item) >= 0 } @@ -1197,7 +1205,7 @@ internal extension Array { } else { return nil } - } + }*/ /** Sorts the array by the value returned from the block, in ascending order @@ -1205,7 +1213,7 @@ internal extension Array { - parameter block: the block to use to sort by - returns: an array sorted by that block, in ascending order */ - func sortUsing (block: ((T) -> U)) -> [T] { + func sortUsing (block: ((Element) -> U)) -> [Element] { return self.sort({ block($0.0) < block($0.1) }) } @@ -1291,7 +1299,7 @@ internal extension Array { - parameter range: - returns: Array of values */ - @available(*, unavailable, message="use the '[U](range)' constructor") static func range (range: Range) -> [U] { + @available(*, unavailable, message="use the '[U](range)' constructor") func range (range: Range) -> [U] { return [U](range) } @@ -1310,7 +1318,7 @@ internal extension Array { return [] } - return Array(self[Range(start: start, end: end)] as ArraySlice) + return Array(self[Range(start: start, end: end)] as ArraySlice) } /** @@ -1345,34 +1353,34 @@ internal extension Array { let indexes = [first, second] + rest return indexes.map { self[$0] } } - } + /** Remove an element from the array */ -public func - (first: [T], second: T) -> [T] { +public func - (first: [Element], second: Element) -> [Element] { return first - [second] } /** Difference operator */ -public func - (first: [T], second: [T]) -> [T] { +public func - (first: [Element], second: [Element]) -> [Element] { return first.difference(second) } /** Intersection operator */ -public func & (first: [T], second: [T]) -> [T] { +public func & (first: [Element], second: [Element]) -> [Element] { return first.intersection(second) } /** Union operator */ -public func | (first: [T], second: [T]) -> [T] { +public func | (first: [Element], second: [Element]) -> [Element] { return first.union(second) } /** diff --git a/ExSwift/ExSwift.swift b/ExSwift/ExSwift.swift index 6060c7b..72bcad3 100644 --- a/ExSwift/ExSwift.swift +++ b/ExSwift/ExSwift.swift @@ -52,7 +52,7 @@ public class ExSwift { - parameter function: Function to wrap - returns: Wrapper function */ - public class func after (n: Int, function: Void -> T) -> (Void -> T?) { + /*public class func after (n: Int, function: Void -> T) -> (Void -> T?) { func callAfter (args: Any?...) -> T { return function() } @@ -60,7 +60,7 @@ public class ExSwift { let f = ExSwift.after(n, function: callAfter) return { f([nil]) } - } + }*/ /** Creates a wrapper function that invokes function once. @@ -97,14 +97,14 @@ public class ExSwift { - parameter function: Function to wrap - returns: Wrapper function */ - public class func once (function: Void -> T) -> (Void -> T) { + /*public class func once (function: Void -> T) -> (Void -> T) { let f = ExSwift.once { (params: Any?...) -> T in return function() } return { f([nil]) } - } + }*/ /** Creates a wrapper that, when called, invokes function with any additional @@ -245,29 +245,28 @@ extension ExSwift { */ internal class func bridgeObjCObject (object: S) -> [T] { var result = [T]() - let reflection = reflect(object) + let reflection = Mirror(reflecting: object) + let mirrorChildrenCollection = AnyRandomAccessCollection(reflection.children) // object has an Objective-C type if let obj = object as? T { // object has type T result.append(obj) - } else if reflection.disposition == .ObjCObject { + } else if reflection.subjectType == NSArray.self { // If it is an NSArray, flattening will produce the expected result if let array = object as? NSArray { result += array.flatten() - } else if let bridged = reflection.value as? T { + } else if let bridged = mirrorChildrenCollection as? T { result.append(bridged) } - } else if reflection.disposition == .IndexContainer { + } else if object is Array { // object is a native Swift array // recursively convert each item - (0.. () -> [OutType] { var result = [OutType]() - let reflection = reflect(self) - - for i in 0.. Self { - return self.dynamicType(timeIntervalSinceReferenceDate: self.timeIntervalSinceReferenceDate + n) + return self.dynamicType.init(timeIntervalSinceReferenceDate: self.timeIntervalSinceReferenceDate + n) } } // MARK: Arithmetic diff --git a/ExSwift/Range.swift b/ExSwift/Range.swift index af4d568..a0a3683 100644 --- a/ExSwift/Range.swift +++ b/ExSwift/Range.swift @@ -16,7 +16,7 @@ internal extension Range { - parameter function: Function to call */ func times (function: () -> ()) { - each { (current: T) -> () in + each { (current: Element) -> () in function() } } @@ -26,7 +26,7 @@ internal extension Range { - parameter function: Function to invoke */ - func times (function: (T) -> ()) { + func times (function: (Element) -> ()) { each (function) } @@ -35,7 +35,7 @@ internal extension Range { - parameter function: Function to invoke */ - func each (function: (T) -> ()) { + func each (function: (Element) -> ()) { for i in self { function(i) } @@ -46,8 +46,8 @@ internal extension Range { - returns: Each element of the range in an array */ - func toArray () -> [T] { - var result: [T] = [] + func toArray () -> [Element] { + var result: [Element] = [] for i in self { result.append(i) } diff --git a/ExSwift/Sequence.swift b/ExSwift/Sequence.swift index 1b2c043..d0d3b54 100644 --- a/ExSwift/Sequence.swift +++ b/ExSwift/Sequence.swift @@ -15,7 +15,7 @@ internal extension AnySequence { - returns: First element of the sequence if present */ - var first: T? { + var first: Element? { let generator = self.generate() return generator.next() } @@ -26,7 +26,7 @@ internal extension AnySequence { - parameter call: Function to call for each element - returns: True if call returns true for any element of self */ - func any (call: (T) -> Bool) -> Bool { + func any (call: (Element) -> Bool) -> Bool { let generator = self.generate() while let nextItem = generator.next() { if call(nextItem) { @@ -42,7 +42,7 @@ internal extension AnySequence { - parameter index: - returns: Object at index in sequence, nil if index is out of bounds */ - func get (index: Int) -> T? { + func get (index: Int) -> Element? { let generator = self.generate() for _ in 0..<(index - 1) { generator.next() @@ -56,7 +56,7 @@ internal extension AnySequence { - parameter range: - returns: Subsequence in range */ - func get (range: Range) -> AnySequence { + func get (range: Range) -> AnySequence { return self.skip(range.startIndex).take(range.endIndex - range.startIndex) } @@ -85,7 +85,7 @@ internal extension AnySequence { - parameter n: Number of elements to skip - returns: Sequence from n to the end */ - func skip (n: Int) -> AnySequence { + func skip (n: Int) -> AnySequence { let generator = self.generate() for _ in 0.. Bool) -> AnySequence { - return AnySequence(lazy(self).filter(include)) + func filter(include: (Element) -> Bool) -> AnySequence { + return AnySequence(self.filter(include)) } /** @@ -109,7 +109,7 @@ internal extension AnySequence { - parameter exclude: Function invoked to test elements for exlcusion from the sequence - returns: Filtered sequence */ - func reject (exclude: (T -> Bool)) -> AnySequence { + func reject (exclude: (Element -> Bool)) -> AnySequence { return self.filter { return !exclude($0) } @@ -121,7 +121,7 @@ internal extension AnySequence { - parameter condition: A function which returns a boolean if an element satisfies a given condition or not - returns: Elements of the sequence starting with the element which does not meet the condition */ - func skipWhile(condition:(T) -> Bool) -> AnySequence { + func skipWhile(condition:(Element) -> Bool) -> AnySequence { let generator = self.generate() let checkingGenerator = self.generate() @@ -144,10 +144,10 @@ internal extension AnySequence { - parameter item: The item to search for - returns: true if self contains item */ - func contains (item: T) -> Bool { + func contains (item: Element) -> Bool { let generator = self.generate() while let nextItem = generator.next() { - if nextItem as! T == item { + if nextItem as! Element == item { return true } } @@ -160,7 +160,7 @@ internal extension AnySequence { - parameter n: Number of elements to take - returns: First n elements */ - func take (n: Int) -> AnySequence { + func take (n: Int) -> AnySequence { return AnySequence(TakeSequence(self, n)) } @@ -170,7 +170,7 @@ internal extension AnySequence { - parameter condition: A function which returns a boolean if an element satisfies a given condition or not. - returns: Elements of the sequence up until an element does not meet the condition */ - func takeWhile (condition:(T?) -> Bool) -> AnySequence { + func takeWhile (condition:(Element?) -> Bool) -> AnySequence { return AnySequence(TakeWhileSequence(self, condition)) } @@ -179,8 +179,8 @@ internal extension AnySequence { - returns: Each element of the sequence in an array */ - func toArray () -> [T] { - var result: [T] = [] + func toArray () -> [Element] { + var result: [Element] = [] for item in self { result.append(item) } diff --git a/ExSwift/String.swift b/ExSwift/String.swift index 38bea6b..fd6cccf 100644 --- a/ExSwift/String.swift +++ b/ExSwift/String.swift @@ -31,7 +31,7 @@ public extension String { return nil } - let range = Range(start: advance(startIndex, range.startIndex), end: advance(startIndex, range.endIndex)) + let range = Range(start: startIndex.advancedBy(range.startIndex), end: startIndex.advancedBy(range.endIndex)) return self[range] } @@ -91,9 +91,7 @@ public extension String { - returns: Array of substrings */ func explode (separator: Character) -> [String] { - return split(self.characters, isSeparator: { (element: Character) -> Bool in - return element == separator - }).map { String($0) } + return self.characters.split { $0 == separator }.map { String($0) } } /** From 9b0dcabb3a56883701b7f8b39b517050c39e2762 Mon Sep 17 00:00:00 2001 From: Andrew Ng Date: Tue, 26 Jan 2016 17:18:20 -0800 Subject: [PATCH 04/11] Swift 3.0 will remove C-Style for loop, ++, and -- --- ExSwift/Array.swift | 19 ++++++++++--------- ExSwift/Dictionary.swift | 4 ++-- ExSwift/ExSwift.swift | 4 ++-- ExSwift/Sequence.swift | 6 +++--- 4 files changed, 17 insertions(+), 16 deletions(-) diff --git a/ExSwift/Array.swift b/ExSwift/Array.swift index c4c98d5..e8f013a 100644 --- a/ExSwift/Array.swift +++ b/ExSwift/Array.swift @@ -371,7 +371,8 @@ internal extension Array { */ mutating func shuffle () { - for var i = self.count - 1; i >= 1; i-- { + for i in (1..= 1; i -= 1 { let j = Int.random(max: i) swap(&self[i], &self[j]) } @@ -737,7 +738,7 @@ internal extension Array { if n == 1 { endArray += [array] } - for var i = 0; i < n; i++ { + for var i = 0; i < n; i += 1 { permutationHelper(n - 1, array: &array, endArray: &endArray) let j = n % 2 == 0 ? i : 0; //(array[j], array[n - 1]) = (array[n - 1], array[j]) @@ -790,7 +791,7 @@ internal extension Array { let groupKey = group(item) if result.has(groupKey) { - result[groupKey]!++ + result[groupKey]! += 1 } else { result[groupKey] = 1 } @@ -825,12 +826,12 @@ internal extension Array { combinations.append(combination) var i = indexes.count - 1 while i >= 0 && indexes[i] == self.count - 1 { - i-- + i -= 1 } if i < 0 { break } - indexes[i]++ + indexes[i] += 1 (i+1).upTo(indexes.count - 1) { j in indexes[j] = indexes[i] } @@ -859,12 +860,12 @@ internal extension Array { combinations.append(combination) var i = indexes.count - 1 while i >= 0 && indexes[i] == i + offset { - i-- + i -= 1 } if i < 0 { break } - i++ + i += 1 let start = indexes[i-1] + 1 for j in (i-1)..: SequenceType { public func generate() -> AnyGenerator { var count = 0 var generator = self.sequence.generate() - return anyGenerator { - count++ + return AnyGenerator { + count += 1 if count > self.n { return nil } else { From 594744288c4abb9658d138e76a212fe3439853eb Mon Sep 17 00:00:00 2001 From: Andrew Ng Date: Tue, 26 Jan 2016 17:57:40 -0800 Subject: [PATCH 05/11] More Swift 3 changes --- ExSwift/Array.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ExSwift/Array.swift b/ExSwift/Array.swift index e8f013a..52d06c1 100644 --- a/ExSwift/Array.swift +++ b/ExSwift/Array.swift @@ -738,7 +738,7 @@ internal extension Array { if n == 1 { endArray += [array] } - for var i = 0; i < n; i += 1 { + for i in 0 ..< n { permutationHelper(n - 1, array: &array, endArray: &endArray) let j = n % 2 == 0 ? i : 0; //(array[j], array[n - 1]) = (array[n - 1], array[j]) @@ -1319,7 +1319,7 @@ internal extension Array { return [] } - return Array(self[Range(start: start, end: end)] as ArraySlice) + return Array(self[start ..< end] as ArraySlice) } /** @@ -1329,7 +1329,7 @@ internal extension Array { - returns: Subarray or nil if the index is out of bounds */ subscript (interval: HalfOpenInterval) -> Array { - return self[rangeAsArray: Range(start: interval.start, end: interval.end)] + return self[rangeAsArray: interval.start ..< interval.end] } /** From 785438ea5455606751614dbef5217f164be8fef8 Mon Sep 17 00:00:00 2001 From: Andrew Ng Date: Mon, 18 Apr 2016 18:36:57 -0700 Subject: [PATCH 06/11] Minor Swift 3.0 changes --- ExSwift/Array.swift | 15 +++++++++++---- ExSwift/Sequence.swift | 2 +- ExSwift/String.swift | 5 +++-- 3 files changed, 15 insertions(+), 7 deletions(-) diff --git a/ExSwift/Array.swift b/ExSwift/Array.swift index 52d06c1..ea63b85 100644 --- a/ExSwift/Array.swift +++ b/ExSwift/Array.swift @@ -247,7 +247,10 @@ internal extension Array { - parameter step: The number of elements to progress between each partition. Set to n if not supplied. - returns: Array partitioned into n element arrays, starting step elements apart. */ - func partition (var n: Int, var step: Int? = nil) -> [Array] { + func partition (n: Int, step: Int? = nil) -> [Array] { + var n = n + var step = step + var result = [Array]() // If no step is supplied move n each step. @@ -276,8 +279,10 @@ internal extension Array { the last partition may less than n elements long. - returns: Array partitioned into n element arrays, starting step elements apart. */ - func partition (var n: Int, var step: Int? = nil, pad: Array?) -> [Array] { + func partition (n: Int, step: Int? = nil, pad: Array?) -> [Array] { var result = [Array]() + var n = n + var step = step // If no step is supplied move n each step. if step == nil { @@ -323,8 +328,10 @@ internal extension Array { - parameter step: The number of elements to progress between each partition. Set to n if not supplied. - returns: Array partitioned into n element arrays, starting step elements apart. */ - func partitionAll (var n: Int, var step: Int? = nil) -> [Array] { + func partitionAll (n: Int, step: Int? = nil) -> [Array] { var result = [Array]() + var n = n + var step = step // If no step is supplied move n each step. if step == nil { @@ -1339,7 +1346,7 @@ internal extension Array { - returns: Subarray or nil if the index is out of bounds */ subscript (interval: ClosedInterval) -> Array { - return self[rangeAsArray: Range(start: interval.start, end: interval.end + 1)] + return self[rangeAsArray: interval.start ..< (interval.end + 1)] } /** diff --git a/ExSwift/Sequence.swift b/ExSwift/Sequence.swift index 2f2be33..e249928 100644 --- a/ExSwift/Sequence.swift +++ b/ExSwift/Sequence.swift @@ -229,7 +229,7 @@ public struct TakeWhileSequence: SequenceType { public func generate() -> AnyGenerator { var generator = self.sequence.generate() var endConditionMet = false - return anyGenerator { + return AnyGenerator { let next: S.Generator.Element? = generator.next() if !endConditionMet { endConditionMet = !self.condition(next) diff --git a/ExSwift/String.swift b/ExSwift/String.swift index fd6cccf..bc6e060 100644 --- a/ExSwift/String.swift +++ b/ExSwift/String.swift @@ -31,7 +31,7 @@ public extension String { return nil } - let range = Range(start: startIndex.advancedBy(range.startIndex), end: startIndex.advancedBy(range.endIndex)) + let range = startIndex.advancedBy(range.startIndex) ..< startIndex.advancedBy(range.endIndex) return self[range] } @@ -213,7 +213,8 @@ public extension String { - parameter charset: Chars to use in the random string - returns: Random string */ - static func random (var length len: Int = 0, charset: String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") -> String { + static func random (length: Int = 0, charset: String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") -> String { + var len = length if len < 1 { len = Int.random(max: 16) From 2ca8514ee7026706e92be6ee06464732f5e2f0d9 Mon Sep 17 00:00:00 2001 From: Andrew Ng Date: Wed, 14 Sep 2016 20:39:43 -0700 Subject: [PATCH 07/11] Swift 3 changes --- ExSwift/Array.swift | 198 +++++++++++++++++++++------------------ ExSwift/Dictionary.swift | 46 ++++----- ExSwift/Double.swift | 8 +- ExSwift/ExSwift.swift | 58 ++++++------ ExSwift/Float.swift | 4 +- ExSwift/Int.swift | 62 ++++++------ ExSwift/NSArray.swift | 2 +- ExSwift/NSDate.swift | 156 +++++++++++++++--------------- ExSwift/Range.swift | 174 +++++++++++++++++++++++----------- ExSwift/Sequence.swift | 66 ++++++------- ExSwift/String.swift | 83 +++++++++------- 11 files changed, 475 insertions(+), 382 deletions(-) diff --git a/ExSwift/Array.swift b/ExSwift/Array.swift index ea63b85..1244c9b 100644 --- a/ExSwift/Array.swift +++ b/ExSwift/Array.swift @@ -7,10 +7,30 @@ // import Foundation +fileprivate func < (lhs: T?, rhs: T?) -> Bool { + switch (lhs, rhs) { + case let (l?, r?): + return l < r + case (nil, _?): + return true + default: + return false + } +} + +fileprivate func >= (lhs: T?, rhs: T?) -> Bool { + switch (lhs, rhs) { + case let (l?, r?): + return l >= r + default: + return !(lhs < rhs) + } +} + internal extension Array { - private var indexesInterval: HalfOpenInterval { return HalfOpenInterval(0, self.count) } + fileprivate var indexesInterval: Range { return (0 ..< self.count) } /** Checks if self contains a list of items. @@ -18,7 +38,7 @@ internal extension Array { - parameter items: Items to search for - returns: true if self contains all the items */ - func contains (items: Element...) -> Bool { + func contains (_ items: Element...) -> Bool { return items.all { (item: Element) -> Bool in self.indexOf(item) >= 0 } } @@ -28,7 +48,7 @@ internal extension Array { - parameter values: Arrays to subtract - returns: Difference of self and the input arrays */ - func difference (values: [Element]...) -> [Element] { + func difference (_ values: [Element]...) -> [Element] { var result = [Element]() @@ -57,12 +77,12 @@ internal extension Array { - parameter values: Arrays to intersect - returns: Array of unique values contained in all the dictionaries and self */ - func intersection (values: [U]...) -> Array { + func intersection (_ values: [U]...) -> 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], ... @@ -91,7 +111,7 @@ internal extension Array { - parameter values: Arrays - returns: Union array of unique values */ - func union (values: [U]...) -> Array { + func union (_ values: [U]...) -> Array { var result = self @@ -112,7 +132,7 @@ internal extension Array { - returns: First element of the array if not empty */ - @available(*, unavailable, message="use the 'first' property instead") func first () -> Element? { + @available(*, unavailable, message: "use the 'first' property instead") func first () -> Element? { return first } @@ -121,7 +141,7 @@ internal extension Array { - returns: Last element of the array if not empty */ - @available(*, unavailable, message="use the 'last' property instead") func last () -> Element? { + @available(*, unavailable, message: "use the 'last' property instead") func last () -> Element? { return last } @@ -131,7 +151,7 @@ internal extension Array { - parameter item: The item to search for - returns: Matched item or nil */ - func find (item: U) -> Element? { + func find (_ item: U) -> Element? { if let index: Int = indexOf(item) { return self[index] } @@ -145,7 +165,7 @@ internal extension Array { - parameter condition: A function which returns a boolean if an element satisfies a given condition or not. - returns: First matched item or nil */ - func find (condition: Element -> Bool) -> Element? { + func find (_ condition: (Element) -> Bool) -> Element? { return takeFirst(condition) } @@ -155,9 +175,9 @@ internal extension Array { - parameter item: The item to search for - returns: Index of the matched item or nil */ - func indexOf (item: U) -> Int? { + func indexOf (_ item: U) -> Int? { if item is Element { - return self.indexOf({ (object) -> Bool in + return self.index(where: { (object) -> Bool in return (object as! U) == item }) } @@ -171,9 +191,9 @@ internal extension Array { - parameter item: The item to search for - returns: Index of the matched item or nil */ - func lastIndexOf (item: U) -> Int? { + func lastIndexOf (_ item: U) -> Int? { if item is Element { - for (index, value) in self.reverse().enumerate() { + for (index, value) in self.reversed().enumerated() { if value as! U == item { return count - 1 - index } @@ -191,7 +211,7 @@ internal extension Array { - parameter index: - returns: Object at index in self */ - func get (index: Int) -> Element? { + func get (_ index: Int) -> Element? { return index >= 0 && index < count ? self[index] : nil @@ -203,7 +223,7 @@ internal extension Array { - parameter range: - returns: Subarray in range */ - func get (range: Range) -> Array { + func get (_ range: Range) -> Array { return Array(self[range]) @@ -216,7 +236,7 @@ internal extension Array { - parameter arrays: Arrays to zip - returns: Array of grouped elements */ - func zip (arrays: Any...) -> [[Any?]] { + func zip (_ arrays: Any...) -> [[Any?]] { var result = [[Any?]]() @@ -247,7 +267,7 @@ internal extension Array { - parameter step: The number of elements to progress between each partition. Set to n if not supplied. - returns: Array partitioned into n element arrays, starting step elements apart. */ - func partition (n: Int, step: Int? = nil) -> [Array] { + func partition (_ n: Int, step: Int? = nil) -> [Array] { var n = n var step = step @@ -262,7 +282,7 @@ internal extension Array { if n < 1 { n = 0 } // Allow 0 if user wants [[],[],[]] for some reason. if n > count { return [[]] } - for i in 0.stride(through: count - n, by: step!) { + for i in stride(from: 0, through: count - n, by: step!) { result += [Array(self[i..<(i + n)])] } @@ -279,7 +299,7 @@ internal extension Array { the last partition may less than n elements long. - returns: Array partitioned into n element arrays, starting step elements apart. */ - func partition (n: Int, step: Int? = nil, pad: Array?) -> [Array] { + func partition (_ n: Int, step: Int? = nil, pad: Array?) -> [Array] { var result = [Array]() var n = n var step = step @@ -299,7 +319,7 @@ internal extension Array { n = 0 } - for i in 0.stride(through: count, by: step!) { + for i in stride(from: 0, through: count, by: step!) { var end = i + n if end > count { @@ -328,7 +348,7 @@ internal extension Array { - parameter step: The number of elements to progress between each partition. Set to n if not supplied. - returns: Array partitioned into n element arrays, starting step elements apart. */ - func partitionAll (n: Int, step: Int? = nil) -> [Array] { + func partitionAll (_ n: Int, step: Int? = nil) -> [Array] { var result = [Array]() var n = n var step = step @@ -341,7 +361,7 @@ internal extension Array { if step < 1 { step = 1 } // Less than 1 results in an infinite loop. if n < 1 { n = 0 } // Allow 0 if user wants [[],[],[]] for some reason. - for i in 0.stride(through: count, by: step!) { + for i in stride(from: 0, through: count, by: step!) { result += [Array(self[i..<(i + n)])] } @@ -354,7 +374,7 @@ internal extension Array { - parameter cond: Function which takes an element and produces an equatable result. - returns: Array partitioned in order, splitting via results of cond. */ - func partitionBy (cond: (Element) -> Element) -> [Array] { + func partitionBy (_ cond: (Element) -> Element) -> [Array] { var result = [Array]() var lastValue: Element? = nil @@ -378,7 +398,7 @@ internal extension Array { */ mutating func shuffle () { - for i in (1..= 1; i -= 1 { let j = Int.random(max: i) swap(&self[i], &self[j]) @@ -423,7 +443,7 @@ internal extension Array { return map { return $0 as! U - }.maxElement()! + }.max()! } @@ -436,7 +456,7 @@ internal extension Array { return map { return $0 as! U - }.minElement()! + }.min()! } @@ -445,7 +465,7 @@ internal extension Array { - returns: Max value in terms of call(value) */ - func maxBy (call: (Element) -> (U)) -> Element? { + func maxBy (_ call: (Element) -> (U)) -> Element? { if let firstValue = self.first { var maxElement: Element = firstValue @@ -470,7 +490,7 @@ internal extension Array { - returns: Min value in terms of call(value) */ - func minBy (call: (Element) -> (U)) -> Element? { + func minBy (_ call: (Element) -> (U)) -> Element? { if let firstValue = self.first { var minElement: Element = firstValue @@ -495,7 +515,7 @@ internal extension Array { - parameter call: Function to call for each element */ - func each (call: (Element) -> ()) { + func each (_ call: (Element) -> ()) { for item in self { call(item) @@ -508,9 +528,9 @@ internal extension Array { - parameter call: Function to call for each element */ - func each (call: (Int, Element) -> ()) { + func each (_ call: (Int, Element) -> ()) { - for (index, item) in self.enumerate() { + for (index, item) in self.enumerated() { call(index, item) } @@ -521,8 +541,8 @@ internal extension Array { - parameter call: Function to call for each element */ - @available(*, unavailable, message="use 'reverse().each' instead") func eachRight (call: (Element) -> ()) { - reverse().each(call) + @available(*, unavailable, message: "use 'reverse().each' instead") func eachRight (_ call: (Element) -> ()) { + reversed().each(call) } /** @@ -530,8 +550,8 @@ internal extension Array { - parameter call: Function to call for each element */ - @available(*, unavailable, message="use 'reverse().each' instead") func eachRight (call: (Int, Element) -> ()) { - for (index, item) in reverse().enumerate() { + @available(*, unavailable, message: "use 'reverse().each' instead") func eachRight (_ call: (Int, Element) -> ()) { + for (index, item) in reversed().enumerated() { call(count - index - 1, item) } } @@ -542,7 +562,7 @@ internal extension Array { - parameter test: Function to call for each element - returns: true if test returns true for any element of self */ - func any (test: (Element) -> Bool) -> Bool { + func any (_ test: (Element) -> Bool) -> Bool { for item in self { if test(item) { return true @@ -558,7 +578,7 @@ internal extension Array { - parameter test: Function to call for each element - returns: True if test returns true for all the elements in self */ - func all (test: (Element) -> Bool) -> Bool { + func all (_ test: (Element) -> Bool) -> Bool { for item in self { if !test(item) { return false @@ -574,7 +594,7 @@ internal extension Array { - parameter exclude: Function invoked to test elements for the exclusion from the array - returns: Filtered array */ - func reject (exclude: (Element -> Bool)) -> Array { + func reject (_ exclude: ((Element) -> Bool)) -> Array { return filter { return !exclude($0) } @@ -586,7 +606,7 @@ internal extension Array { - parameter n: Number of elements to take - returns: First n elements */ - func take (n: Int) -> Array { + func take (_ n: Int) -> Array { return Array(self[0.. Bool) -> Array { + func takeWhile (_ condition: (Element) -> Bool) -> Array { var lastTrue = -1 - for (index, value) in self.enumerate() { + for (index, value) in self.enumerated() { if condition(value) { lastTrue = index } else { @@ -618,7 +638,7 @@ internal extension Array { - parameter condition: A function which returns a boolean if an element satisfies a given condition or not. - returns: The first element in the array to meet the condition */ - func takeFirst (condition: (Element) -> Bool) -> Element? { + func takeFirst (_ condition: (Element) -> Bool) -> Element? { for value in self { if condition(value) { @@ -636,7 +656,7 @@ internal extension Array { - parameter n: Number of elements to take - returns: Last n elements */ - func tail (n: Int) -> Array { + func tail (_ n: Int) -> Array { return Array(self[(count - n).. Array { + func skip (_ n: Int) -> Array { return n > count ? [] : Array(self[Int(n).. Bool) -> Array { + func skipWhile (_ condition: (Element) -> Bool) -> Array { var lastTrue = -1 - for (index, value) in self.enumerate() { + for (index, value) in self.enumerated() { if condition(value) { lastTrue = index } else { @@ -699,7 +719,7 @@ internal extension Array { - parameter call: The closure to use to determine uniqueness - returns: The set of elements for which call(element) is unique */ - func uniqueBy (call: (Element) -> (Element)) -> [Element] { + func uniqueBy (_ call: (Element) -> (Element)) -> [Element] { var result: [Element] = [] var uniqueItems: [Element] = [] @@ -720,7 +740,7 @@ internal extension Array { - parameter length: The length of each permutation - returns: All permutations of a given length within an array */ - func permutation (length: Int) -> [[Element]] { + func permutation (_ length: Int) -> [[Element]] { if length < 0 || length > self.count { return [] } else if length == 0 { @@ -741,7 +761,7 @@ internal extension Array { Recursive helper method where all of the permutation-generating work is done This is Heap's algorithm */ - private func permutationHelper(n: Int, inout array: [Element], inout endArray: [[Element]]) -> [[Element]] { + fileprivate func permutationHelper(_ n: Int, array: inout [Element], endArray: inout [[Element]]) -> [[Element]] { if n == 1 { endArray += [array] } @@ -813,7 +833,7 @@ internal extension Array { - parameter length: - returns: Combinations */ - func repeatedCombination (length: Int) -> [[Element]] { + func repeatedCombination (_ length: Int) -> [[Element]] { if length < 0 { return [] } @@ -852,7 +872,7 @@ internal extension Array { - parameter length: - returns: Combinations */ - func combination (length: Int) -> [[Element]] { + func combination (_ length: Int) -> [[Element]] { if length < 0 || length > self.count { return [] } @@ -887,7 +907,7 @@ internal extension Array { - parameter length: The length of each permutations :returns All of the permutations of this array of a given length, allowing repeats */ - func repeatedPermutation(length: Int) -> [[Element]] { + func repeatedPermutation(_ length: Int) -> [[Element]] { if length < 1 { return [] } @@ -896,7 +916,7 @@ internal extension Array { return permutationIndexes.map({ $0.map({ i in self[i] }) }) } - private func repeatedPermutationHelper(seed: [Int], length: Int, arrayLength: Int, inout permutationIndexes: [[Int]]) { + fileprivate func repeatedPermutationHelper(_ seed: [Int], length: Int, arrayLength: Int, permutationIndexes: inout [[Int]]) { if seed.count == length { permutationIndexes.append(seed) return @@ -914,7 +934,7 @@ internal extension Array { - parameter test: Function to call for each element - returns: the number of elements meeting the condition */ - func countWhere (test: (Element) -> Bool) -> Int { + func countWhere (_ test: (Element) -> Bool) -> Int { var result = 0 @@ -927,7 +947,7 @@ internal extension Array { return result } - func eachIndex (call: (Int) -> ()) -> () { + func eachIndex (_ call: @escaping (Int) -> ()) -> () { (0.. [[Element]] { // () -> [[U]] { + func transposition (_ array: [[Element]]) -> [[Element]] { // () -> [[U]] { let maxWidth: Int = array.map({ $0.count }).max() - var transposition = [[Element]](count: maxWidth, repeatedValue: []) + var transposition = [[Element]](repeating: [], count: maxWidth) (0.. () { + mutating func fill (_ object: Element) -> () { (0.. (separator: C) -> C? { + func implode (_ separator: C) -> C? { if Element.self is C.Type { - if let joined = unsafeBitCast(self, [C].self).joinWithSeparator(separator) as? C { + if let joined = unsafeBitCast(self, to: [C].self).joined(separator: separator) as? C { return joined } else { return nil @@ -1011,7 +1031,7 @@ internal extension Array { - parameter mapFunction: - returns: Accumulated value and mapped array */ - func mapAccum (initial: U, mapFunction map: (U, Element) -> (U, V)) -> (U, [V]) { + func mapAccum (_ initial: U, mapFunction map: (U, Element) -> (U, V)) -> (U, [V]) { var mapped = [V]() var acc = initial @@ -1027,9 +1047,9 @@ internal extension Array { /** self.reduce with initial value self.first() */ - func reduce (combine: (Element, Element) -> Element) -> Element? { + func reduce (_ combine: (Element, Element) -> Element) -> Element? { if let firstElement = first { - return skip(1).reduce(firstElement, combine: combine) + return skip(1).reduce(firstElement, combine) } return nil @@ -1038,15 +1058,15 @@ internal extension Array { /** self.reduce from right to left */ - @available(*, unavailable, message="use 'reverse().reduce' instead") func reduceRight (initial: U, combine: (U, Element) -> U) -> U { - return reverse().reduce(initial, combine: combine) + @available(*, unavailable, message: "use 'reverse().reduce' instead") func reduceRight (_ initial: U, combine: (U, Element) -> U) -> U { + return reversed().reduce(initial, combine) } /** self.reduceRight with initial value self.last() */ - @available(*, unavailable, message="use 'reverse().reduce' instead") func reduceRight (combine: (Element, Element) -> Element) -> Element? { - return reverse().reduce(combine) + @available(*, unavailable, message: "use 'reverse().reduce' instead") func reduceRight (_ combine: (Element, Element) -> Element) -> Element? { + return reversed().reduce(combine) } /** @@ -1055,7 +1075,7 @@ internal extension Array { - parameter indexes: Indexes of the elements to get - returns: Array with the elements at indexes */ - func at (indexes: Int...) -> Array { + func at (_ indexes: Int...) -> Array { return indexes.map { self.get($0)! } } @@ -1065,7 +1085,7 @@ internal extension Array { - parameter keySelector: - returns: A dictionary */ - func toDictionary (keySelector:(Element) -> U) -> [U: Element] { + func toDictionary (_ keySelector:(Element) -> U) -> [U: Element] { var result: [U: Element] = [:] for item in self { result[keySelector(item)] = item @@ -1080,7 +1100,7 @@ internal extension Array { - parameter transform: - returns: A dictionary */ - func toDictionary (transform: (Element) -> (key: K, value: V)?) -> [K: V] { + func toDictionary (_ transform: (Element) -> (key: K, value: V)?) -> [K: V] { var result: [K: V] = [:] for item in self { if let entry = transform(item) { @@ -1135,8 +1155,8 @@ internal extension Array { - parameter isOrderedBefore: Comparison function. - returns: An array that is sorted according to the given function */ - @available(*, unavailable, message="use 'sort' instead") func sortBy (isOrderedBefore: (Element, Element) -> Bool) -> [Element] { - return sort(isOrderedBefore) + @available(*, unavailable, message: "use 'sort' instead") func sortBy (_ isOrderedBefore: (Element, Element) -> Bool) -> [Element] { + return sorted(by: isOrderedBefore) } /** @@ -1145,7 +1165,7 @@ internal extension Array { - parameter n: the number of times to cycle through - parameter block: the block to run for each element in each cycle */ - func cycle (n: Int? = nil, block: (Element) -> ()) { + func cycle (_ n: Int? = nil, block: (Element) -> ()) { var cyclesRun = 0 while true { if let n = n { @@ -1170,7 +1190,7 @@ internal extension Array { - parameter block: the block to run each time - returns: the min element, or nil if there are no items for which the block returns true */ - func bSearch (block: (Element) -> (Bool)) -> Element? { + func bSearch (_ block: (Element) -> (Bool)) -> Element? { if count == 0 { return nil } @@ -1221,8 +1241,8 @@ internal extension Array { - parameter block: the block to use to sort by - returns: an array sorted by that block, in ascending order */ - func sortUsing (block: ((Element) -> U)) -> [Element] { - return self.sort({ block($0.0) < block($0.1) }) + func sortUsing (_ block: ((Element) -> U)) -> [Element] { + return self.sorted(by: { block($0.0) < block($0.1) }) } /** @@ -1245,7 +1265,7 @@ internal extension Array { - parameter newElement: Element to append */ - mutating func push (newElement: Element) { + mutating func push (_ newElement: Element) { return append(newElement) } @@ -1260,7 +1280,7 @@ internal extension Array { return nil } - return removeAtIndex(0) + return self.remove(at: 0) } @@ -1269,8 +1289,8 @@ internal extension Array { - parameter newElement: Object to prepend */ - mutating func unshift (newElement: Element) { - insert(newElement, atIndex: 0) + mutating func unshift (_ newElement: Element) { + insert(newElement, at: 0) } /** @@ -1279,7 +1299,7 @@ internal extension Array { - parameter newArray: Array to insert - parameter atIndex: Where to insert the array */ - mutating func insert (newArray: Array, atIndex: Int) { + mutating func insert (_ newArray: Array, atIndex: Int) { self = take(atIndex) + newArray + skip(atIndex) } @@ -1288,10 +1308,10 @@ internal extension Array { - parameter element: Element to remove */ - mutating func remove (element: U) { + mutating func remove (_ element: U) { let anotherSelf = self - removeAll(keepCapacity: true) + removeAll(keepingCapacity: true) anotherSelf.each { (index: Int, current: Element) in @@ -1307,7 +1327,7 @@ internal extension Array { - parameter range: - returns: Array of values */ - @available(*, unavailable, message="use the '[U](range)' constructor") func range (range: Range) -> [U] { + @available(*, unavailable, message: "use the '[U](range)' constructor") func range (_ range: Range) -> [U] { return [U](range) } @@ -1319,8 +1339,8 @@ internal extension Array { */ subscript (rangeAsArray rangeAsArray: Range) -> Array { // Fix out of bounds indexes - let start = Swift.max(0, rangeAsArray.startIndex) - let end = Swift.min(rangeAsArray.endIndex, count) + let start = Swift.max(0, rangeAsArray.lowerBound) + let end = Swift.min(rangeAsArray.upperBound, count) if start > end { return [] @@ -1335,7 +1355,7 @@ internal extension Array { - parameter interval: Interval of indexes of the subarray elements - returns: Subarray or nil if the index is out of bounds */ - subscript (interval: HalfOpenInterval) -> Array { + subscript (interval: Range) -> Array { return self[rangeAsArray: interval.start ..< interval.end] } @@ -1345,7 +1365,7 @@ internal extension Array { - parameter interval: Interval of indexes of the subarray elements - returns: Subarray or nil if the index is out of bounds */ - subscript (interval: ClosedInterval) -> Array { + subscript (interval: ClosedRange) -> Array { return self[rangeAsArray: interval.start ..< (interval.end + 1)] } diff --git a/ExSwift/Dictionary.swift b/ExSwift/Dictionary.swift index feb823e..3e5ec0d 100644 --- a/ExSwift/Dictionary.swift +++ b/ExSwift/Dictionary.swift @@ -18,7 +18,7 @@ internal extension Dictionary { - parameter dictionaries: Dictionaries to subtract - returns: Difference of self and the input dictionaries */ - func difference (dictionaries: [Key: V]...) -> [Key: V] { + func difference (_ dictionaries: [Key: V]...) -> [Key: V] { var result = [Key: V]() @@ -32,7 +32,7 @@ internal extension Dictionary { for dictionary in dictionaries { for (key, value) in dictionary { if result.has(key) && result[key] == value { - result.removeValueForKey(key) + result.removeValue(forKey: key) } } } @@ -47,7 +47,7 @@ internal extension Dictionary { - parameter dictionaries: Dictionaries to join - returns: Union of self and the input dictionaries */ - func union (dictionaries: Dictionary...) -> Dictionary { + func union (_ dictionaries: Dictionary...) -> Dictionary { var result = self @@ -68,7 +68,7 @@ internal extension Dictionary { - parameter values: Dictionaries to intersect - returns: Dictionary of [key: value] couples contained in all the dictionaries and self */ - func intersection (dictionaries: [K: V]...) -> [K: V] { + func intersection (_ 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 @@ -93,8 +93,8 @@ internal extension Dictionary { - parameter key: Key to check - returns: true if the key exists */ - func has (key: Key) -> Bool { - return indexForKey(key) != nil + func has (_ key: Key) -> Bool { + return index(forKey: key) != nil } /** @@ -104,7 +104,7 @@ internal extension Dictionary { - parameter mapFunction: - returns: Mapped array */ - func toArray (map: (Key, Value) -> V) -> [V] { + func toArray (_ map: (Key, Value) -> V) -> [V] { var mapped = [V]() @@ -123,7 +123,7 @@ internal extension Dictionary { - parameter mapFunction: - returns: Mapped dictionary */ - func mapValues (map: (Key, Value) -> V) -> [Key: V] { + func mapValues (_ map: (Key, Value) -> V) -> [Key: V] { var mapped = [Key: V]() @@ -142,7 +142,7 @@ internal extension Dictionary { - parameter mapFunction: - returns: Mapped dictionary */ - func mapFilterValues (map: (Key, Value) -> V?) -> [Key: V] { + func mapFilterValues (_ map: (Key, Value) -> V?) -> [Key: V] { var mapped = [Key: V]() @@ -163,7 +163,7 @@ internal extension Dictionary { - parameter mapFunction: - returns: Mapped dictionary */ - func mapFilter (map: (Key, Value) -> (K, V)?) -> [K: V] { + func mapFilter (_ map: (Key, Value) -> (K, V)?) -> [K: V] { var mapped = [K: V]() @@ -184,7 +184,7 @@ internal extension Dictionary { - parameter mapFunction: - returns: Mapped dictionary */ - func map (map: (Key, Value) -> (K, V)) -> [K: V] { + func map (_ map: (Key, Value) -> (K, V)) -> [K: V] { var mapped = [K: V]() @@ -202,7 +202,7 @@ internal extension Dictionary { - parameter eachFunction: Function to inovke on each loop */ - func each (each: (Key, Value) -> ()) { + func each (_ each: (Key, Value) -> ()) { for (key, value) in self { each(key, value) @@ -217,7 +217,7 @@ internal extension Dictionary { - parameter testFunction: Function called to test each key, value - returns: Filtered dictionary */ - func filter (test: (Key, Value) -> Bool) -> Dictionary { + func filter (_ test: (Key, Value) -> Bool) -> Dictionary { var result = Dictionary() @@ -239,7 +239,7 @@ internal extension Dictionary { - parameter groupingFunction: - returns: Grouped dictionary */ - func groupBy (group: (Key, Value) -> T) -> [T: [Value]] { + func groupBy (_ group: (Key, Value) -> T) -> [T: [Value]] { var result = [T: [Value]]() @@ -265,7 +265,7 @@ internal extension Dictionary { - parameter groupingFunction: Function called to define the grouping key - returns: Grouped dictionary */ - func countBy (group: (Key, Value) -> (T)) -> [T: Int] { + func countBy (_ group: (Key, Value) -> (T)) -> [T: Int] { var result = [T: Int]() @@ -290,7 +290,7 @@ internal extension Dictionary { - parameter test: Function to call for each element - returns: true if test returns true for all the elements in self */ - func all (test: (Key, Value) -> (Bool)) -> Bool { + func all (_ test: (Key, Value) -> (Bool)) -> Bool { for (key, value) in self { if !test(key, value) { @@ -308,7 +308,7 @@ internal extension Dictionary { - parameter test: Function to call for each element - returns: true if test returns true for any element of self */ - func any (test: (Key, Value) -> (Bool)) -> Bool { + func any (_ test: (Key, Value) -> (Bool)) -> Bool { for (key, value) in self { if test(key, value) { @@ -327,7 +327,7 @@ internal extension Dictionary { - parameter test: Function to call for each element - returns: the number of elements meeting the condition */ - func countWhere (test: (Key, Value) -> (Bool)) -> Int { + func countWhere (_ test: (Key, Value) -> (Bool)) -> Int { var result = 0 @@ -346,7 +346,7 @@ internal extension Dictionary { - parameter keys: Whitelisted keys - returns: Filtered dictionary */ - func pick (keys: [Key]) -> Dictionary { + func pick (_ keys: [Key]) -> Dictionary { return filter { (key: Key, _) -> Bool in return keys.contains(key) } @@ -358,8 +358,8 @@ internal extension Dictionary { - parameter keys: Whitelisted keys - returns: Filtered dictionary */ - func pick (keys: Key...) -> Dictionary { - return pick(unsafeBitCast(keys, [Key].self)) + func pick (_ keys: Key...) -> Dictionary { + return pick(unsafeBitCast(keys, to: [Key].self)) } /** @@ -368,7 +368,7 @@ internal extension Dictionary { - parameter keys: Keys to get - returns: Dictionary with the given keys */ - func at (keys: Key...) -> Dictionary { + func at (_ keys: Key...) -> Dictionary { return pick(keys) } @@ -380,7 +380,7 @@ internal extension Dictionary { */ mutating func shift () -> (Key, Value)? { if let key = keys.first { - return (key, removeValueForKey(key)!) + return (key, removeValue(forKey: key)!) } return nil diff --git a/ExSwift/Double.swift b/ExSwift/Double.swift index ace4b9e..4fb4ec5 100644 --- a/ExSwift/Double.swift +++ b/ExSwift/Double.swift @@ -62,7 +62,7 @@ public extension Double { - parameter max: Upper bound - returns: Clamped value */ - func clamp (min: Double, _ max: Double) -> Double { + func clamp (_ min: Double, _ max: Double) -> Double { return Swift.max(min, Swift.min(max, self)) } @@ -72,8 +72,8 @@ public extension Double { :params: increment the increment to round to */ - func roundToNearest(increment: Double) -> Double { - let remainder = self % increment + func roundToNearest(_ increment: Double) -> Double { + let remainder = self.truncatingRemainder(dividingBy: increment) return remainder < increment / 2 ? self - remainder : self - remainder + increment } @@ -84,7 +84,7 @@ public extension Double { :params: max - returns: Random number */ - static func random(min: Double = 0, max: Double) -> Double { + static func random(_ min: Double = 0, max: Double) -> Double { let diff = max - min; let rand = Double(arc4random() % (UInt32(RAND_MAX) + 1)) return ((rand / Double(RAND_MAX)) * diff) + min; diff --git a/ExSwift/ExSwift.swift b/ExSwift/ExSwift.swift index e770d7c..cab7c00 100644 --- a/ExSwift/ExSwift.swift +++ b/ExSwift/ExSwift.swift @@ -8,14 +8,14 @@ import Foundation -infix operator =~ {} -infix operator |~ {} -infix operator .. {} -infix operator <=> {} +infix operator =~ +infix operator |~ +infix operator .. +infix operator <=> public typealias Ex = ExSwift -public class ExSwift { +open class ExSwift { /** Creates a wrapper that, executes function only after being called n times. @@ -24,9 +24,9 @@ public class ExSwift { - parameter function: Function to wrap - returns: Wrapper function */ - public class func after (n: Int, function: (P...) -> T) -> ((P...) -> T?) { + open class func after (_ n: Int, function: @escaping (P...) -> T) -> ((P...) -> T?) { - typealias Function = [P] -> T + typealias Function = ([P]) -> T var times = n @@ -34,7 +34,7 @@ public class ExSwift { (params: P...) -> T? in // Workaround for the now illegal (T...) type. - let adaptedFunction = unsafeBitCast(function, Function.self) + let adaptedFunction = unsafeBitCast(function, to: Function.self) times -= 1 if times <= 0 { return adaptedFunction(params) @@ -69,9 +69,9 @@ public class ExSwift { - parameter function: Function to wrap - returns: Wrapper function */ - public class func once (function: (P...) -> T) -> ((P...) -> T) { + open class func once (_ function: @escaping (P...) -> T) -> ((P...) -> T) { - typealias Function = [P] -> T + typealias Function = ([P]) -> T var returnValue: T? = nil @@ -81,7 +81,7 @@ public class ExSwift { return returnValue! } - let adaptedFunction = unsafeBitCast(function, Function.self) + let adaptedFunction = unsafeBitCast(function, to: Function.self) returnValue = adaptedFunction(params) return returnValue! @@ -114,11 +114,11 @@ public class ExSwift { - parameter parameters: Arguments to prepend - returns: Wrapper function */ - public class func partial (function: (P...) -> T, _ parameters: P...) -> ((P...) -> T) { - typealias Function = [P] -> T + open class func partial (_ function: @escaping (P...) -> T, _ parameters: P...) -> ((P...) -> T) { + typealias Function = ([P]) -> T return { (params: P...) -> T in - let adaptedFunction = unsafeBitCast(function, Function.self) + let adaptedFunction = unsafeBitCast(function, to: Function.self) return adaptedFunction(parameters + params) } } @@ -131,11 +131,11 @@ public class ExSwift { - parameter parameters: Arguments to pass to function - returns: Wrapper function */ - public class func bind (function: (P...) -> T, _ parameters: P...) -> (Void -> T) { - typealias Function = [P] -> T + open class func bind (_ function: @escaping (P...) -> T, _ parameters: P...) -> ((Void) -> T) { + typealias Function = ([P]) -> T return { Void -> T in - let adaptedFunction = unsafeBitCast(function, Function.self) + let adaptedFunction = unsafeBitCast(function, to: Function.self) return adaptedFunction(parameters) } } @@ -146,7 +146,7 @@ public class ExSwift { - parameter function: Function with one parameter to cache - returns: Wrapper function */ - public class func cached (function: P -> R) -> (P -> R) { + open class func cached (_ function: @escaping (P) -> R) -> ((P) -> R) { var cache = [P:R]() return { (param: P) -> R in @@ -169,15 +169,15 @@ public class ExSwift { - parameter hash: Parameters based hashing function that computes the key used to store each result in the cache - returns: Wrapper function */ - public class func cached (function: (P...) -> R, hash: ((P...) -> P)) -> ((P...) -> R) { - typealias Function = [P] -> R - typealias Hash = [P] -> P + open class func cached (_ function: @escaping (P...) -> R, hash: @escaping ((P...) -> P)) -> ((P...) -> R) { + typealias Function = ([P]) -> R + typealias Hash = ([P]) -> P var cache = [P:R]() return { (params: P...) -> R in - let adaptedFunction = unsafeBitCast(function, Function.self) - let adaptedHash = unsafeBitCast(hash, Hash.self) + let adaptedFunction = unsafeBitCast(function, to: Function.self) + let adaptedHash = unsafeBitCast(hash, to: Hash.self) let key = adaptedHash(params) @@ -197,7 +197,7 @@ public class ExSwift { - parameter function: Function to cache - returns: Wrapper function */ - public class func cached (function: (P...) -> R) -> ((P...) -> R) { + open class func cached (_ function: @escaping (P...) -> R) -> ((P...) -> R) { return cached(function, hash: { (params: P...) -> P in return params[0] }) } @@ -208,15 +208,15 @@ public class ExSwift { - parameter ignoreCase: If true the NSRegularExpression is created with the NSRegularExpressionOptions.CaseInsensitive flag - returns: NSRegularExpression object */ - internal class func regex (pattern: String, ignoreCase: Bool = false) throws -> NSRegularExpression? { + internal class func regex (_ pattern: String, ignoreCase: Bool = false) throws -> NSRegularExpression? { - var options = NSRegularExpressionOptions.DotMatchesLineSeparators.rawValue + var options = NSRegularExpression.Options.dotMatchesLineSeparators.rawValue if ignoreCase { - options = NSRegularExpressionOptions.CaseInsensitive.rawValue | options + options = NSRegularExpression.Options.caseInsensitive.rawValue | options } - return try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions(rawValue: options)) + return try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options(rawValue: options)) } @@ -243,7 +243,7 @@ extension ExSwift { * @param object Object to convert * @returns Flattenend array of converted values */ - internal class func bridgeObjCObject (object: S) -> [T] { + internal class func bridgeObjCObject (_ object: S) -> [T] { var result = [T]() let reflection = Mirror(reflecting: object) let mirrorChildrenCollection = AnyRandomAccessCollection(reflection.children) diff --git a/ExSwift/Float.swift b/ExSwift/Float.swift index 3362f60..bf06338 100644 --- a/ExSwift/Float.swift +++ b/ExSwift/Float.swift @@ -62,7 +62,7 @@ public extension Float { - parameter max: Upper bound - returns: Clamped value */ - func clamp (min: Float, _ max: Float) -> Float { + func clamp (_ min: Float, _ max: Float) -> Float { return Swift.max(min, Swift.min(max, self)) } @@ -73,7 +73,7 @@ public extension Float { - parameter max: - returns: Random number */ - static func random(min: Float = 0, max: Float) -> Float { + static func random(_ min: Float = 0, max: Float) -> Float { let diff = max - min; let rand = Float(arc4random() % (UInt32(RAND_MAX) + 1)) return ((rand / Float(RAND_MAX)) * diff) + min; diff --git a/ExSwift/Int.swift b/ExSwift/Int.swift index 5503fe5..c658c87 100644 --- a/ExSwift/Int.swift +++ b/ExSwift/Int.swift @@ -15,8 +15,8 @@ public extension Int { - parameter function: Function to call */ - func times (function: Void -> T) { - (0.. (_ function: @escaping (Void) -> T) { + (0.. Void) { - (0.. Void) { + (0.. (function: (Int) -> T) { - (0.. (_ function: @escaping (Int) -> T) { + (0.. ()) { + func upTo (_ limit: Int, function: (Int) -> ()) { if limit < self { return } @@ -75,12 +75,12 @@ public extension Int { - parameter limit: Last value to pass - parameter function: Function to invoke */ - func downTo (limit: Int, function: (Int) -> ()) { + func downTo (_ limit: Int, function: (Int) -> ()) { if limit > self { return } - Array(Array(limit...self).reverse()).each(function) + Array(Array(limit...self).reversed()).each(function) } /** @@ -89,8 +89,8 @@ public extension Int { - parameter range: Clamping range - returns: Clamped value */ - func clamp (range: Range) -> Int { - return clamp(range.startIndex, range.endIndex - 1) + func clamp (_ range: Range) -> Int { + return clamp(range.lowerBound, range.upperBound - 1) } /** @@ -100,7 +100,7 @@ public extension Int { - parameter max: Upper bound - returns: Clamped value */ - func clamp (min: Int, _ max: Int) -> Int { + func clamp (_ min: Int, _ max: Int) -> Int { return Swift.max(min, Swift.min(max, self)) } @@ -111,12 +111,12 @@ public extension Int { - parameter strict: If true, "<" is used for comparison - returns: true if in range */ - func isIn (range: Range, strict: Bool = false) -> Bool { + func isIn (_ range: Range, strict: Bool = false) -> Bool { if strict { - return range.startIndex < self && self < range.endIndex - 1 + return range.lowerBound < self && self < range.upperBound - 1 } - return range.startIndex <= self && self <= range.endIndex - 1 + return range.lowerBound <= self && self <= range.upperBound - 1 } /** @@ -125,7 +125,7 @@ public extension Int { - parameter interval: Interval to check - returns: true if in the interval */ - func isIn (interval: ClosedInterval) -> Bool { + func isIn (_ interval: ClosedRange) -> Bool { return interval.contains(self) } @@ -135,7 +135,7 @@ public extension Int { - parameter interval: Interval to check - returns: true if in the interval */ - func isIn (interval: HalfOpenInterval) -> Bool { + func isIn (_ interval: Range) -> Bool { return interval.contains(self) } @@ -172,7 +172,7 @@ public extension Int { - parameter n: - returns: GCD */ - func gcd (n: Int) -> Int { + func gcd (_ n: Int) -> Int { return n == 0 ? self : n.gcd(self % n) } @@ -182,7 +182,7 @@ public extension Int { - parameter n: - returns: LCM */ - func lcm (n: Int) -> Int { + func lcm (_ n: Int) -> Int { return (self * n).abs() / gcd(n) } @@ -202,7 +202,7 @@ public extension Int { - parameter max: Maximum value to return - returns: Random integer */ - static func random(min: Int = 0, max: Int) -> Int { + static func random(_ min: Int = 0, max: Int) -> Int { return Int(arc4random_uniform(UInt32((max - min) + 1))) + min } @@ -213,43 +213,43 @@ public extension Int { */ public extension Int { - var years: NSTimeInterval { + var years: TimeInterval { return 365 * self.days } - var year: NSTimeInterval { + var year: TimeInterval { return self.years } - var days: NSTimeInterval { + var days: TimeInterval { return 24 * self.hours } - var day: NSTimeInterval { + var day: TimeInterval { return self.days } - var hours: NSTimeInterval { + var hours: TimeInterval { return 60 * self.minutes } - var hour: NSTimeInterval { + var hour: TimeInterval { return self.hours } - var minutes: NSTimeInterval { + var minutes: TimeInterval { return 60 * self.seconds } - var minute: NSTimeInterval { + var minute: TimeInterval { return self.minutes } - var seconds: NSTimeInterval { - return NSTimeInterval(self) + var seconds: TimeInterval { + return TimeInterval(self) } - var second: NSTimeInterval { + var second: TimeInterval { return self.seconds } diff --git a/ExSwift/NSArray.swift b/ExSwift/NSArray.swift index 6b74a2e..5748efc 100644 --- a/ExSwift/NSArray.swift +++ b/ExSwift/NSArray.swift @@ -55,7 +55,7 @@ public extension NSArray { if let array = item as? NSArray { result += array.flattenAny() } else { - result.append(item) + result.append(item as AnyObject) } } diff --git a/ExSwift/NSDate.swift b/ExSwift/NSDate.swift index f4e4d4b..f0b9288 100644 --- a/ExSwift/NSDate.swift +++ b/ExSwift/NSDate.swift @@ -8,7 +8,7 @@ import Foundation -public extension NSDate { +public extension Date { // MARK: NSDate Manipulation @@ -24,49 +24,49 @@ public extension NSDate { - parameter years: number of years to add - returns: the NSDate computed */ - public func add(seconds seconds: Int = 0, minutes: Int = 0, hours: Int = 0, days: Int = 0, weeks: Int = 0, months: Int = 0, years: Int = 0) -> NSDate { - let calendar = NSCalendar.currentCalendar() + public func add(seconds: Int = 0, minutes: Int = 0, hours: Int = 0, days: Int = 0, weeks: Int = 0, months: Int = 0, years: Int = 0) -> Date { + let calendar = Calendar.current let version = floor(NSFoundationVersionNumber) if version <= NSFoundationVersionNumber10_9_2 { - var component = NSDateComponents() - component.setValue(seconds, forComponent: .Second) + var component = DateComponents() + (component as NSDateComponents).setValue(seconds, forComponent: .second) - var date : NSDate! = calendar.dateByAddingComponents(component, toDate: self, options: [])! - component = NSDateComponents() - component.setValue(minutes, forComponent: .Minute) - date = calendar.dateByAddingComponents(component, toDate: date, options: [])! + var date : Date! = (calendar as NSCalendar).date(byAdding: component, to: self, options: [])! + component = DateComponents() + (component as NSDateComponents).setValue(minutes, forComponent: .minute) + date = (calendar as NSCalendar).date(byAdding: component, to: date, options: [])! - component = NSDateComponents() - component.setValue(hours, forComponent: .Hour) - date = calendar.dateByAddingComponents(component, toDate: date, options: [])! + component = DateComponents() + (component as NSDateComponents).setValue(hours, forComponent: .hour) + date = (calendar as NSCalendar).date(byAdding: component, to: date, options: [])! - component = NSDateComponents() - component.setValue(days, forComponent: .Day) - date = calendar.dateByAddingComponents(component, toDate: date, options: [])! + component = DateComponents() + (component as NSDateComponents).setValue(days, forComponent: .day) + date = (calendar as NSCalendar).date(byAdding: component, to: date, options: [])! - component = NSDateComponents() - component.setValue(weeks, forComponent: .WeekOfMonth) - date = calendar.dateByAddingComponents(component, toDate: date, options: [])! + component = DateComponents() + (component as NSDateComponents).setValue(weeks, forComponent: .weekOfMonth) + date = (calendar as NSCalendar).date(byAdding: component, to: date, options: [])! - component = NSDateComponents() - component.setValue(months, forComponent: .Month) - date = calendar.dateByAddingComponents(component, toDate: date, options: [])! + component = DateComponents() + (component as NSDateComponents).setValue(months, forComponent: .month) + date = (calendar as NSCalendar).date(byAdding: component, to: date, options: [])! - component = NSDateComponents() - component.setValue(years, forComponent: .Year) - date = calendar.dateByAddingComponents(component, toDate: date, options: [])! + component = DateComponents() + (component as NSDateComponents).setValue(years, forComponent: .year) + date = (calendar as NSCalendar).date(byAdding: component, to: date, options: [])! return date } - let options = NSCalendarOptions(rawValue: 0) - var date : NSDate! = calendar.dateByAddingUnit(NSCalendarUnit.Second, value: seconds, toDate: self, options: options) - date = calendar.dateByAddingUnit(NSCalendarUnit.Minute, value: minutes, toDate: date, options: options) - date = calendar.dateByAddingUnit(NSCalendarUnit.Day, value: days, toDate: date, options: options) - date = calendar.dateByAddingUnit(NSCalendarUnit.Hour, value: hours, toDate: date, options: options) - date = calendar.dateByAddingUnit(NSCalendarUnit.WeekOfMonth, value: weeks, toDate: date, options: options) - date = calendar.dateByAddingUnit(NSCalendarUnit.Month, value: months, toDate: date, options: options) - date = calendar.dateByAddingUnit(NSCalendarUnit.Year, value: years, toDate: date, options: options) + let options = NSCalendar.Options(rawValue: 0) + var date : Date! = (calendar as NSCalendar).date(byAdding: NSCalendar.Unit.second, value: seconds, to: self, options: options) + date = (calendar as NSCalendar).date(byAdding: NSCalendar.Unit.minute, value: minutes, to: date, options: options) + date = (calendar as NSCalendar).date(byAdding: NSCalendar.Unit.day, value: days, to: date, options: options) + date = (calendar as NSCalendar).date(byAdding: NSCalendar.Unit.hour, value: hours, to: date, options: options) + date = (calendar as NSCalendar).date(byAdding: NSCalendar.Unit.weekOfMonth, value: weeks, to: date, options: options) + date = (calendar as NSCalendar).date(byAdding: NSCalendar.Unit.month, value: months, to: date, options: options) + date = (calendar as NSCalendar).date(byAdding: NSCalendar.Unit.year, value: years, to: date, options: options) return date } @@ -76,7 +76,7 @@ public extension NSDate { - parameter seconds: number of seconds to add - returns: the NSDate computed */ - public func addSeconds (seconds: Int) -> NSDate { + public func addSeconds (_ seconds: Int) -> Date { return add(seconds: seconds) } @@ -86,7 +86,7 @@ public extension NSDate { - parameter minutes: number of minutes to add - returns: the NSDate computed */ - public func addMinutes (minutes: Int) -> NSDate { + public func addMinutes (_ minutes: Int) -> Date { return add(minutes: minutes) } @@ -96,7 +96,7 @@ public extension NSDate { - parameter hours: number of hours to add - returns: the NSDate computed */ - public func addHours(hours: Int) -> NSDate { + public func addHours(_ hours: Int) -> Date { return add(hours: hours) } @@ -106,7 +106,7 @@ public extension NSDate { - parameter days: number of days to add - returns: the NSDate computed */ - public func addDays(days: Int) -> NSDate { + public func addDays(_ days: Int) -> Date { return add(days: days) } @@ -116,7 +116,7 @@ public extension NSDate { - parameter weeks: number of weeks to add - returns: the NSDate computed */ - public func addWeeks(weeks: Int) -> NSDate { + public func addWeeks(_ weeks: Int) -> Date { return add(weeks: weeks) } @@ -128,7 +128,7 @@ public extension NSDate { - returns: the NSDate computed */ - public func addMonths(months: Int) -> NSDate { + public func addMonths(_ months: Int) -> Date { return add(months: months) } @@ -138,7 +138,7 @@ public extension NSDate { - parameter years: number of year to add - returns: the NSDate computed */ - public func addYears(years: Int) -> NSDate { + public func addYears(_ years: Int) -> Date { return add(years: years) } @@ -150,8 +150,8 @@ public extension NSDate { - parameter date: NSDate to compare - returns: True if self is after the input NSDate, false otherwise */ - public func isAfter(date: NSDate) -> Bool{ - return (self.compare(date) == NSComparisonResult.OrderedDescending) + public func isAfter(_ date: Date) -> Bool{ + return (self.compare(date) == ComparisonResult.orderedDescending) } /** @@ -160,8 +160,8 @@ public extension NSDate { - parameter date: NSDate to compare - returns: True if self is before the input NSDate, false otherwise */ - public func isBefore(date: NSDate) -> Bool{ - return (self.compare(date) == NSComparisonResult.OrderedAscending) + public func isBefore(_ date: Date) -> Bool{ + return (self.compare(date) == ComparisonResult.orderedAscending) } @@ -172,7 +172,7 @@ public extension NSDate { */ public var year : Int { get { - return getComponent(.Year) + return getComponent(.year) } } @@ -181,7 +181,7 @@ public extension NSDate { */ public var month : Int { get { - return getComponent(.Month) + return getComponent(.month) } } @@ -190,7 +190,7 @@ public extension NSDate { */ public var weekday : Int { get { - return getComponent(.Weekday) + return getComponent(.weekday) } } @@ -199,7 +199,7 @@ public extension NSDate { */ public var weekMonth : Int { get { - return getComponent(.WeekOfMonth) + return getComponent(.weekOfMonth) } } @@ -209,7 +209,7 @@ public extension NSDate { */ public var days : Int { get { - return getComponent(.Day) + return getComponent(.day) } } @@ -219,7 +219,7 @@ public extension NSDate { public var hours : Int { get { - return getComponent(.Hour) + return getComponent(.hour) } } @@ -228,7 +228,7 @@ public extension NSDate { */ public var minutes : Int { get { - return getComponent(.Minute) + return getComponent(.minute) } } @@ -237,7 +237,7 @@ public extension NSDate { */ public var seconds : Int { get { - return getComponent(.Second) + return getComponent(.second) } } @@ -248,68 +248,68 @@ public extension NSDate { - returns: the value of the component */ - public func getComponent (component : NSCalendarUnit) -> Int { - let calendar = NSCalendar.currentCalendar() - let components = calendar.components(component, fromDate: self) + public func getComponent (_ component : NSCalendar.Unit) -> Int { + let calendar = Calendar.current + let components = (calendar as NSCalendar).components(component, from: self) - return components.valueForComponent(component) + return components.value(for: component) } } -extension NSDate: Strideable { - public func distanceTo(other: NSDate) -> NSTimeInterval { +extension Date: Strideable { + public func distance(to other: Date) -> TimeInterval { return other - self } - public func advancedBy(n: NSTimeInterval) -> Self { - return self.dynamicType.init(timeIntervalSinceReferenceDate: self.timeIntervalSinceReferenceDate + n) + public func advanced(by n: TimeInterval) -> Date { + return type(of: self).init(timeIntervalSinceReferenceDate: self.timeIntervalSinceReferenceDate + n) } } // MARK: Arithmetic -func +(date: NSDate, timeInterval: Int) -> NSDate { - return date + NSTimeInterval(timeInterval) +func +(date: Date, timeInterval: Int) -> Date { + return date + TimeInterval(timeInterval) } -func -(date: NSDate, timeInterval: Int) -> NSDate { - return date - NSTimeInterval(timeInterval) +func -(date: Date, timeInterval: Int) -> Date { + return date - TimeInterval(timeInterval) } -func +=(inout date: NSDate, timeInterval: Int) { +func +=(date: inout Date, timeInterval: Int) { date = date + timeInterval } -func -=(inout date: NSDate, timeInterval: Int) { +func -=(date: inout Date, timeInterval: Int) { date = date - timeInterval } -func +(date: NSDate, timeInterval: Double) -> NSDate { - return date.dateByAddingTimeInterval(NSTimeInterval(timeInterval)) +func +(date: Date, timeInterval: Double) -> Date { + return date.addingTimeInterval(TimeInterval(timeInterval)) } -func -(date: NSDate, timeInterval: Double) -> NSDate { - return date.dateByAddingTimeInterval(NSTimeInterval(-timeInterval)) +func -(date: Date, timeInterval: Double) -> Date { + return date.addingTimeInterval(TimeInterval(-timeInterval)) } -func +=(inout date: NSDate, timeInterval: Double) { +func +=(date: inout Date, timeInterval: Double) { date = date + timeInterval } -func -=(inout date: NSDate, timeInterval: Double) { +func -=(date: inout Date, timeInterval: Double) { date = date - timeInterval } -func -(date: NSDate, otherDate: NSDate) -> NSTimeInterval { - return date.timeIntervalSinceDate(otherDate) +func -(date: Date, otherDate: Date) -> TimeInterval { + return date.timeIntervalSince(otherDate) } -public func ==(lhs: NSDate, rhs: NSDate) -> Bool { - return lhs.compare(rhs) == NSComparisonResult.OrderedSame +public func ==(lhs: Date, rhs: Date) -> Bool { + return lhs.compare(rhs) == ComparisonResult.orderedSame } -extension NSDate: Comparable { +extension Date: Comparable { } -public func <(lhs: NSDate, rhs: NSDate) -> Bool { - return lhs.compare(rhs) == NSComparisonResult.OrderedAscending +public func <(lhs: Date, rhs: Date) -> Bool { + return lhs.compare(rhs) == ComparisonResult.orderedAscending } diff --git a/ExSwift/Range.swift b/ExSwift/Range.swift index a0a3683..b82afeb 100644 --- a/ExSwift/Range.swift +++ b/ExSwift/Range.swift @@ -8,73 +8,135 @@ import Foundation -internal extension Range { - - /** - For each element in the range invokes function. - - - parameter function: Function to call - */ - func times (function: () -> ()) { - each { (current: Element) -> () in - function() - } +public extension CountableRange { + + /** + For each element in the range invokes function. + + - parameter function: Function to call + */ + public func times (_ function: () -> ()) { + each { (current: Bound) -> () in + function() } + } + + /** + For each element in the range invokes function passing the element as argument. - /** - For each element in the range invokes function passing the element as argument. - - - parameter function: Function to invoke - */ - func times (function: (Element) -> ()) { - each (function) + - parameter function: Function to invoke + */ + public func times (_ function: (Bound) -> ()) { + each (function) + } + + /** + For each element in the range invokes function passing the element as argument. + + - parameter function: Function to invoke + */ + public func each (_ function: (Bound) -> ()) { + for i in self { + function(i) } + } + + /** + Returns each element of the range in an array + + - returns: Each element of the range in an array + */ + public func toArray () -> [Bound] { + var result: [Bound] = [] + for i in self { + result.append(i) + } + return result + } + + /** + Range of Int with random bounds between from and to (inclusive). + + - parameter from: Lower bound + - parameter to: Upper bound + - returns: Random range + */ + public static func random (_ from: Int, to: Int) -> CountableClosedRange { + let lowerBound = Int.random(from, max: to) + let upperBound = Int.random(lowerBound, max: to) + + return lowerBound...upperBound + } - /** - For each element in the range invokes function passing the element as argument. - - - parameter function: Function to invoke - */ - func each (function: (Element) -> ()) { - for i in self { - function(i) - } +} + +public extension CountableClosedRange { + + /** + For each element in the range invokes function. + + - parameter function: Function to call + */ + public func times (_ function: () -> ()) { + each { (current: Bound) -> () in + function() } + } + + /** + For each element in the range invokes function passing the element as argument. + + - parameter function: Function to invoke + */ + public func times (_ function: (Bound) -> ()) { + each (function) + } - /** - Returns each element of the range in an array - - - returns: Each element of the range in an array - */ - func toArray () -> [Element] { - var result: [Element] = [] - for i in self { - result.append(i) - } - return result + /** + For each element in the range invokes function passing the element as argument. + + - parameter function: Function to invoke + */ + public func each (_ function: (Bound) -> ()) { + for i in self { + function(i) } + } + + /** + Returns each element of the range in an array - /** - Range of Int with random bounds between from and to (inclusive). - - - parameter from: Lower bound - - parameter to: Upper bound - - returns: Random range - */ - static func random (from: Int, to: Int) -> Range { - let lowerBound = Int.random(from, max: to) - let upperBound = Int.random(lowerBound, max: to) - - return lowerBound...upperBound + - returns: Each element of the range in an array + */ + public func toArray () -> [Bound] { + var result: [Bound] = [] + for i in self { + result.append(i) } + return result + } + + /** + Range of Int with random bounds between from and to (inclusive). + + - parameter from: Lower bound + - parameter to: Upper bound + - returns: Random range + */ + public static func random (_ from: Int, to: Int) -> CountableClosedRange { + let lowerBound = Int.random(from, max: to) + let upperBound = Int.random(lowerBound, max: to) + + return lowerBound...upperBound + } } /** -* Operator == to compare 2 ranges first, second by start & end indexes. If first.startIndex is equal to -* second.startIndex and first.endIndex is equal to second.endIndex the ranges are considered equal. -*/ -public func == (first: Range, second: Range) -> Bool { - return first.startIndex == second.startIndex && - first.endIndex == second.endIndex + * Operator == to compare 2 ranges first, second by start & end indexes. If first.startIndex is equal to + * second.startIndex and first.endIndex is equal to second.endIndex the ranges are considered equal. + */ +public func == (first: Range, second: Range) -> Bool { + return first.lowerBound == second.lowerBound && + first.upperBound == second.upperBound } diff --git a/ExSwift/Sequence.swift b/ExSwift/Sequence.swift index e249928..2149ae7 100644 --- a/ExSwift/Sequence.swift +++ b/ExSwift/Sequence.swift @@ -16,7 +16,7 @@ internal extension AnySequence { - returns: First element of the sequence if present */ var first: Element? { - let generator = self.generate() + let generator = self.makeIterator() return generator.next() } @@ -26,8 +26,8 @@ internal extension AnySequence { - parameter call: Function to call for each element - returns: True if call returns true for any element of self */ - func any (call: (Element) -> Bool) -> Bool { - let generator = self.generate() + func any (_ call: (Element) -> Bool) -> Bool { + let generator = self.makeIterator() while let nextItem = generator.next() { if call(nextItem) { return true @@ -42,8 +42,8 @@ internal extension AnySequence { - parameter index: - returns: Object at index in sequence, nil if index is out of bounds */ - func get (index: Int) -> Element? { - let generator = self.generate() + func get (_ index: Int) -> Element? { + let generator = self.makeIterator() for _ in 0..<(index - 1) { generator.next() } @@ -56,8 +56,8 @@ internal extension AnySequence { - parameter range: - returns: Subsequence in range */ - func get (range: Range) -> AnySequence { - return self.skip(range.startIndex).take(range.endIndex - range.startIndex) + func get (_ range: Range) -> AnySequence { + return self.skip(range.lowerBound).take(range.upperBound - range.lowerBound) } /** @@ -66,7 +66,7 @@ internal extension AnySequence { - parameter item: The item to search for - returns: Index of the matched item or nil */ - func indexOf (item: U) -> Int? { + func indexOf (_ item: U) -> Int? { var index = 0 for current in self { if let equatable = current as? U { @@ -85,8 +85,8 @@ internal extension AnySequence { - parameter n: Number of elements to skip - returns: Sequence from n to the end */ - func skip (n: Int) -> AnySequence { - let generator = self.generate() + func skip (_ n: Int) -> AnySequence { + let generator = self.makeIterator() for _ in 0.. Bool) -> AnySequence { + func filter(_ include: (Element) -> Bool) -> AnySequence { return AnySequence(self.filter(include)) } @@ -109,7 +109,7 @@ internal extension AnySequence { - parameter exclude: Function invoked to test elements for exlcusion from the sequence - returns: Filtered sequence */ - func reject (exclude: (Element -> Bool)) -> AnySequence { + func reject (_ exclude: ((Element) -> Bool)) -> AnySequence { return self.filter { return !exclude($0) } @@ -121,9 +121,9 @@ internal extension AnySequence { - parameter condition: A function which returns a boolean if an element satisfies a given condition or not - returns: Elements of the sequence starting with the element which does not meet the condition */ - func skipWhile(condition:(Element) -> Bool) -> AnySequence { - let generator = self.generate() - let checkingGenerator = self.generate() + func skipWhile(_ condition:(Element) -> Bool) -> AnySequence { + let generator = self.makeIterator() + let checkingGenerator = self.makeIterator() var keepSkipping = true @@ -144,8 +144,8 @@ internal extension AnySequence { - parameter item: The item to search for - returns: true if self contains item */ - func contains (item: Element) -> Bool { - let generator = self.generate() + func contains (_ item: Element) -> Bool { + let generator = self.makeIterator() while let nextItem = generator.next() { if nextItem as! Element == item { return true @@ -160,7 +160,7 @@ internal extension AnySequence { - parameter n: Number of elements to take - returns: First n elements */ - func take (n: Int) -> AnySequence { + func take (_ n: Int) -> AnySequence { return AnySequence(TakeSequence(self, n)) } @@ -170,7 +170,7 @@ internal extension AnySequence { - parameter condition: A function which returns a boolean if an element satisfies a given condition or not. - returns: Elements of the sequence up until an element does not meet the condition */ - func takeWhile (condition:(Element?) -> Bool) -> AnySequence { + func takeWhile (_ condition:@escaping (Element?) -> Bool) -> AnySequence { return AnySequence(TakeWhileSequence(self, condition)) } @@ -191,19 +191,19 @@ internal extension AnySequence { /** A sequence adapter that implements the 'take' functionality */ -public struct TakeSequence: SequenceType { - private let sequence: S - private let n: Int +public struct TakeSequence: Sequence { + fileprivate let sequence: S + fileprivate let n: Int public init(_ sequence: S, _ n: Int) { self.sequence = sequence self.n = n } - public func generate() -> AnyGenerator { + public func makeIterator() -> AnyIterator { var count = 0 - var generator = self.sequence.generate() - return AnyGenerator { + var generator = self.sequence.makeIterator() + return AnyIterator { count += 1 if count > self.n { return nil @@ -217,20 +217,20 @@ public struct TakeSequence: SequenceType { /** a sequence adapter that implements the 'takeWhile' functionality */ -public struct TakeWhileSequence: SequenceType { - private let sequence: S - private let condition: (S.Generator.Element?) -> Bool +public struct TakeWhileSequence: Sequence { + fileprivate let sequence: S + fileprivate let condition: (S.Iterator.Element?) -> Bool - public init(_ sequence:S, _ condition:(S.Generator.Element?) -> Bool) { + public init(_ sequence:S, _ condition:@escaping (S.Iterator.Element?) -> Bool) { self.sequence = sequence self.condition = condition } - public func generate() -> AnyGenerator { - var generator = self.sequence.generate() + public func makeIterator() -> AnyIterator { + var generator = self.sequence.makeIterator() var endConditionMet = false - return AnyGenerator { - let next: S.Generator.Element? = generator.next() + return AnyIterator { + let next: S.Iterator.Element? = generator.next() if !endConditionMet { endConditionMet = !self.condition(next) } diff --git a/ExSwift/String.swift b/ExSwift/String.swift index bc6e060..f37e4cb 100644 --- a/ExSwift/String.swift +++ b/ExSwift/String.swift @@ -18,7 +18,7 @@ public extension String { /** self.capitalizedString shorthand */ - var capitalized: String { return capitalizedString } + var capitalized: String { return capitalized } /** Returns the substring in the given range @@ -27,15 +27,26 @@ public extension String { - returns: Substring in range */ subscript (range: Range) -> String? { - if range.startIndex < 0 || range.endIndex > self.length { + if range.lowerBound < 0 || range.upperBound > self.length { return nil } - let range = startIndex.advancedBy(range.startIndex) ..< startIndex.advancedBy(range.endIndex) + let range = characters.index(startIndex, offsetBy: range.lowerBound) ..< characters.index(startIndex, offsetBy: range.upperBound) return self[range] } + subscript (range: CountableRange) -> String? { + if range.lowerBound < 0 || range.upperBound > self.length { + return nil + } + + let range = characters.index(startIndex, offsetBy: range.lowerBound) ..< characters.index(startIndex, offsetBy: range.upperBound) + + return self[range] + } + + /** Equivalent to at. Takes a list of indexes and returns an Array containing the elements at the given indexes in self. @@ -70,7 +81,7 @@ public extension String { - parameter indexes: Positions of the elements to get - returns: Array of characters (as String) */ - func at (indexes: Int...) -> [String] { + func at (_ indexes: Int...) -> [String] { return indexes.map { self[$0]! } } @@ -80,7 +91,7 @@ public extension String { - parameter indexes: Positions of the elements to get - returns: Array of characters (as String) */ - func at (indexes: [Int]) -> [String] { + func at (_ indexes: [Int]) -> [String] { return indexes.map { self[$0]! } } @@ -90,7 +101,7 @@ public extension String { - parameter separator: Character used to split the string - returns: Array of substrings */ - func explode (separator: Character) -> [String] { + func explode (_ separator: Character) -> [String] { return self.characters.split { $0 == separator }.map { String($0) } } @@ -101,11 +112,11 @@ public extension String { - parameter ignoreCase: true for case insensitive matching - returns: Matches found (as [NSTextCheckingResult]) */ - func matches (pattern: String, ignoreCase: Bool = false) throws -> [NSTextCheckingResult]? { + func matches (_ pattern: String, ignoreCase: Bool = false) throws -> [NSTextCheckingResult]? { if let regex = try ExSwift.regex(pattern, ignoreCase: ignoreCase) { // Using map to prevent a possible bug in the compiler - return regex.matchesInString(self, options: [], range: NSMakeRange(0, length)).map { $0 as NSTextCheckingResult } + return regex.matches(in: self, options: [], range: NSMakeRange(0, length)).map { $0 as NSTextCheckingResult } } return nil @@ -119,10 +130,10 @@ public extension String { - parameter ignoreCase: true for case insensitive matching - returns: true if contains match, otherwise false */ - func containsMatch (pattern: String, ignoreCase: Bool = false) throws -> Bool? { + func containsMatch (_ pattern: String, ignoreCase: Bool = false) throws -> Bool? { if let regex = try ExSwift.regex(pattern, ignoreCase: ignoreCase) { let range = NSMakeRange(0, self.characters.count) - return regex.firstMatchInString(self, options: [], range: range) != nil + return regex.firstMatch(in: self, options: [], range: range) != nil } return nil @@ -136,10 +147,10 @@ public extension String { - parameter ignoreCase: true for case insensitive matching - returns: true if contains match, otherwise false */ - func replaceMatches (pattern: String, withString replacementString: String, ignoreCase: Bool = false) throws -> String? { + func replaceMatches (_ pattern: String, withString replacementString: String, ignoreCase: Bool = false) throws -> String? { if let regex = try ExSwift.regex(pattern, ignoreCase: ignoreCase) { let range = NSMakeRange(0, self.characters.count) - return regex.stringByReplacingMatchesInString(self, options: [], range: range, withTemplate: replacementString) + return regex.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: replacementString) } return nil @@ -152,7 +163,7 @@ public extension String { - parameter string: String to insert - returns: String formed from self inserting string at index */ - func insert (index: Int, _ string: String) -> String { + func insert (_ index: Int, _ string: String) -> String { // Edge cases, prepend and append if index > length { return self + string @@ -168,15 +179,15 @@ public extension String { - returns: Stripped string */ - func trimmedLeft (characterSet set: NSCharacterSet = NSCharacterSet.whitespaceAndNewlineCharacterSet()) -> String { - if let range = rangeOfCharacterFromSet(set.invertedSet) { - return self[range.startIndex.. String { + if let range = rangeOfCharacter(from: set.inverted) { + return self[range.lowerBound.. String { + @available(*, unavailable, message: "use 'trimmedLeft' instead") func ltrimmed (_ set: CharacterSet = CharacterSet.whitespacesAndNewlines) -> String { return trimmedLeft(characterSet: set) } @@ -185,15 +196,15 @@ public extension String { - returns: Stripped string */ - func trimmedRight (characterSet set: NSCharacterSet = NSCharacterSet.whitespaceAndNewlineCharacterSet()) -> String { - if let range = rangeOfCharacterFromSet(set.invertedSet, options: NSStringCompareOptions.BackwardsSearch) { - return self[startIndex.. String { + if let range = rangeOfCharacter(from: set.inverted, options: NSString.CompareOptions.backwards) { + return self[startIndex.. String { + @available(*, unavailable, message: "use 'trimmedRight' instead") func rtrimmed (_ set: CharacterSet = CharacterSet.whitespacesAndNewlines) -> String { return trimmedRight(characterSet: set) } @@ -213,7 +224,7 @@ public extension String { - parameter charset: Chars to use in the random string - returns: Random string */ - static func random (length: Int = 0, charset: String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") -> String { + static func random (_ length: Int = 0, charset: String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") -> String { var len = length if len < 1 { @@ -239,7 +250,7 @@ public extension String { */ func toDouble() -> Double? { - let scanner = NSScanner(string: self) + let scanner = Scanner(string: self) var double: Double = 0 if scanner.scanDouble(&double) { @@ -257,7 +268,7 @@ public extension String { */ func toFloat() -> Float? { - let scanner = NSScanner(string: self) + let scanner = Scanner(string: self) var float: Float = 0 if scanner.scanFloat(&float) { @@ -291,7 +302,7 @@ public extension String { - returns: A Bool parsed from the string or nil if it cannot be parsed as a boolean. */ func toBool() -> Bool? { - let text = self.trimmed().lowercaseString + let text = self.trimmed().lowercased() if text == "true" || text == "false" || text == "yes" || text == "no" { return (text as NSString).boolValue } @@ -305,14 +316,14 @@ public extension String { - returns: A NSDate parsed from the string or nil if it cannot be parsed as a date. */ - func toDate(format : String? = "yyyy-MM-dd") -> NSDate? { - let text = self.trimmed().lowercaseString - let dateFmt = NSDateFormatter() - dateFmt.timeZone = NSTimeZone.defaultTimeZone() + func toDate(_ format : String? = "yyyy-MM-dd") -> Date? { + let text = self.trimmed().lowercased() + let dateFmt = DateFormatter() + dateFmt.timeZone = TimeZone.current if let fmt = format { dateFmt.dateFormat = fmt } - return dateFmt.dateFromString(text) + return dateFmt.date(from: text) } /** @@ -321,7 +332,7 @@ public extension String { - returns: A NSDate parsed from the string or nil if it cannot be parsed as a date. */ - func toDateTime(format : String? = "yyyy-MM-dd hh-mm-ss") -> NSDate? { + func toDateTime(_ format : String? = "yyyy-MM-dd hh-mm-ss") -> Date? { return toDate(format) } @@ -346,7 +357,7 @@ public func * (first: String, n: Int) -> String { public func =~ (string: String, pattern: String) throws -> Bool { let regex = try ExSwift.regex(pattern, ignoreCase: false)! - let matches = regex.numberOfMatchesInString(string, options: [], range: NSMakeRange(0, string.length)) + let matches = regex.numberOfMatches(in: string, options: [], range: NSMakeRange(0, string.length)) return matches > 0 @@ -355,7 +366,7 @@ public func =~ (string: String, pattern: String) throws -> Bool { // Pattern matching using a regular expression public func =~ (string: String, regex: NSRegularExpression) -> Bool { - let matches = regex.numberOfMatchesInString(string, options: [], range: NSMakeRange(0, string.length)) + let matches = regex.numberOfMatches(in: string, options: [], range: NSMakeRange(0, string.length)) return matches > 0 @@ -364,7 +375,7 @@ public func =~ (string: String, regex: NSRegularExpression) -> Bool { // This version also allowes to specify case sentitivity public func =~ (string: String, options: (pattern: String, ignoreCase: Bool)) throws -> Bool { - if let matches = try ExSwift.regex(options.pattern, ignoreCase: options.ignoreCase)?.numberOfMatchesInString(string, options: [], range: NSMakeRange(0, string.length)) { + if let matches = try ExSwift.regex(options.pattern, ignoreCase: options.ignoreCase)?.numberOfMatches(in: string, options: [], range: NSMakeRange(0, string.length)) { return matches > 0 } @@ -383,7 +394,7 @@ public func =~ (strings: [String], pattern: String) throws -> Bool { public func =~ (strings: [String], options: (pattern: String, ignoreCase: Bool)) throws -> Bool { - var lastError: ErrorType? + var lastError: Error? let result = strings.all { do { @@ -413,7 +424,7 @@ public func |~ (strings: [String], pattern: String) throws -> Bool { public func |~ (strings: [String], options: (pattern: String, ignoreCase: Bool)) throws -> Bool { - var lastError: ErrorType? + var lastError: Error? let result = strings.any { do { From 0bccf10806700f0e2f73b9298194745d63dfb201 Mon Sep 17 00:00:00 2001 From: Andrew Ng Date: Sun, 18 Sep 2016 12:42:11 -0700 Subject: [PATCH 08/11] more swift 3 changes --- ExSwift/NSArray.swift | 94 ++++---- ExSwift/NSDate.swift | 518 ++++++++++++++++++++---------------------- 2 files changed, 291 insertions(+), 321 deletions(-) diff --git a/ExSwift/NSArray.swift b/ExSwift/NSArray.swift index 5748efc..7fdede7 100644 --- a/ExSwift/NSArray.swift +++ b/ExSwift/NSArray.swift @@ -10,56 +10,56 @@ import Foundation public extension NSArray { - /** - Converts an NSArray object to an OutType[] array containing the items in the NSArray of type OutType. - - - returns: Array of Swift objects - */ - func cast () -> [OutType] { - var result = [OutType]() - - for item : AnyObject in self { - result += Ex.bridgeObjCObject(item) as [OutType] - } - - return result + /** + Converts an NSArray object to an OutType[] array containing the items in the NSArray of type OutType. + + - returns: Array of Swift objects + */ + public func cast () -> [OutType] { + var result = [OutType]() + + for item : Any in self { + result += Ex.bridgeObjCObject(item) as [OutType] } - /** - Flattens a multidimensional NSArray to an OutType[] array - containing the items in the NSArray that can be bridged from their ObjC type to OutType. - - - returns: Flattened array - */ - func flatten () -> [OutType] { - var result = [OutType]() - let mirror = Mirror(reflecting: self) - if let mirrorChildrenCollection = AnyRandomAccessCollection(mirror.children) { - for (_, value) in mirrorChildrenCollection { - result += Ex.bridgeObjCObject(value) as [OutType] - } - } + return result + } + + /** + Flattens a multidimensional NSArray to an OutType[] array + containing the items in the NSArray that can be bridged from their ObjC type to OutType. - return result + - returns: Flattened array + */ + public func flatten () -> [OutType] { + var result = [OutType]() + let mirror = Mirror(reflecting: self) + if let mirrorChildrenCollection = AnyRandomAccessCollection(mirror.children) { + for (_, value) in mirrorChildrenCollection { + result += Ex.bridgeObjCObject(value) as [OutType] + } } - - /** - Flattens a multidimensional NSArray to a [AnyObject]. - - - returns: Flattened array - */ - func flattenAny () -> [AnyObject] { - var result = [AnyObject]() - - for item in self { - if let array = item as? NSArray { - result += array.flattenAny() - } else { - result.append(item as AnyObject) - } - } - - return result + + return result + } + + /** + Flattens a multidimensional NSArray to a [Any]. + + - returns: Flattened array + */ + public func flattenAny () -> [Any] { + var result = [Any]() + + for item in self { + if let array = item as? NSArray { + result += array.flattenAny() + } else { + result.append(item) + } } - + + return result + } + } diff --git a/ExSwift/NSDate.swift b/ExSwift/NSDate.swift index f0b9288..b598acd 100644 --- a/ExSwift/NSDate.swift +++ b/ExSwift/NSDate.swift @@ -9,307 +9,277 @@ import Foundation public extension Date { - - // MARK: NSDate Manipulation - - /** - Returns a new NSDate object representing the date calculated by adding the amount specified to self date - - - parameter seconds: number of seconds to add - - parameter minutes: number of minutes to add - - parameter hours: number of hours to add - - parameter days: number of days to add - - parameter weeks: number of weeks to add - - parameter months: number of months to add - - parameter years: number of years to add - - returns: the NSDate computed - */ - public func add(seconds: Int = 0, minutes: Int = 0, hours: Int = 0, days: Int = 0, weeks: Int = 0, months: Int = 0, years: Int = 0) -> Date { - let calendar = Calendar.current - let version = floor(NSFoundationVersionNumber) - - if version <= NSFoundationVersionNumber10_9_2 { - var component = DateComponents() - (component as NSDateComponents).setValue(seconds, forComponent: .second) - - var date : Date! = (calendar as NSCalendar).date(byAdding: component, to: self, options: [])! - component = DateComponents() - (component as NSDateComponents).setValue(minutes, forComponent: .minute) - date = (calendar as NSCalendar).date(byAdding: component, to: date, options: [])! - - component = DateComponents() - (component as NSDateComponents).setValue(hours, forComponent: .hour) - date = (calendar as NSCalendar).date(byAdding: component, to: date, options: [])! - - component = DateComponents() - (component as NSDateComponents).setValue(days, forComponent: .day) - date = (calendar as NSCalendar).date(byAdding: component, to: date, options: [])! - - component = DateComponents() - (component as NSDateComponents).setValue(weeks, forComponent: .weekOfMonth) - date = (calendar as NSCalendar).date(byAdding: component, to: date, options: [])! - - component = DateComponents() - (component as NSDateComponents).setValue(months, forComponent: .month) - date = (calendar as NSCalendar).date(byAdding: component, to: date, options: [])! - - component = DateComponents() - (component as NSDateComponents).setValue(years, forComponent: .year) - date = (calendar as NSCalendar).date(byAdding: component, to: date, options: [])! - return date - } - - let options = NSCalendar.Options(rawValue: 0) - var date : Date! = (calendar as NSCalendar).date(byAdding: NSCalendar.Unit.second, value: seconds, to: self, options: options) - date = (calendar as NSCalendar).date(byAdding: NSCalendar.Unit.minute, value: minutes, to: date, options: options) - date = (calendar as NSCalendar).date(byAdding: NSCalendar.Unit.day, value: days, to: date, options: options) - date = (calendar as NSCalendar).date(byAdding: NSCalendar.Unit.hour, value: hours, to: date, options: options) - date = (calendar as NSCalendar).date(byAdding: NSCalendar.Unit.weekOfMonth, value: weeks, to: date, options: options) - date = (calendar as NSCalendar).date(byAdding: NSCalendar.Unit.month, value: months, to: date, options: options) - date = (calendar as NSCalendar).date(byAdding: NSCalendar.Unit.year, value: years, to: date, options: options) - return date - } - - /** - Returns a new NSDate object representing the date calculated by adding an amount of seconds to self date - - - parameter seconds: number of seconds to add - - returns: the NSDate computed - */ - public func addSeconds (_ seconds: Int) -> Date { - return add(seconds: seconds) - } - - /** - Returns a new NSDate object representing the date calculated by adding an amount of minutes to self date - - - parameter minutes: number of minutes to add - - returns: the NSDate computed - */ - public func addMinutes (_ minutes: Int) -> Date { - return add(minutes: minutes) - } - - /** - Returns a new NSDate object representing the date calculated by adding an amount of hours to self date - - - parameter hours: number of hours to add - - returns: the NSDate computed - */ - public func addHours(_ hours: Int) -> Date { - return add(hours: hours) - } - - /** - Returns a new NSDate object representing the date calculated by adding an amount of days to self date - - - parameter days: number of days to add - - returns: the NSDate computed - */ - public func addDays(_ days: Int) -> Date { - return add(days: days) - } - - /** - Returns a new NSDate object representing the date calculated by adding an amount of weeks to self date - - - parameter weeks: number of weeks to add - - returns: the NSDate computed - */ - public func addWeeks(_ weeks: Int) -> Date { - return add(weeks: weeks) - } - - - /** - Returns a new NSDate object representing the date calculated by adding an amount of months to self date - - - parameter months: number of months to add - - returns: the NSDate computed - */ - - public func addMonths(_ months: Int) -> Date { - return add(months: months) - } - - /** - Returns a new NSDate object representing the date calculated by adding an amount of years to self date - - - parameter years: number of year to add - - returns: the NSDate computed - */ - public func addYears(_ years: Int) -> Date { - return add(years: years) - } - - // MARK: Date comparison - - /** - Checks if self is after input NSDate - - - parameter date: NSDate to compare - - returns: True if self is after the input NSDate, false otherwise - */ - public func isAfter(_ date: Date) -> Bool{ - return (self.compare(date) == ComparisonResult.orderedDescending) - } - - /** - Checks if self is before input NSDate - - - parameter date: NSDate to compare - - returns: True if self is before the input NSDate, false otherwise - */ - public func isBefore(_ date: Date) -> Bool{ - return (self.compare(date) == ComparisonResult.orderedAscending) - } - - - // MARK: Getter - - /** - Date year - */ - public var year : Int { - get { - return getComponent(.year) - } - } - /** - Date month - */ - public var month : Int { - get { - return getComponent(.month) - } - } - - /** - Date weekday - */ - public var weekday : Int { - get { - return getComponent(.weekday) - } - } + // MARK: NSDate Manipulation - /** - Date weekMonth - */ - public var weekMonth : Int { - get { - return getComponent(.weekOfMonth) - } - } + /** + Returns a new NSDate object representing the date calculated by adding the amount specified to self date + + - parameter seconds: number of seconds to add + - parameter minutes: number of minutes to add + - parameter hours: number of hours to add + - parameter days: number of days to add + - parameter weeks: number of weeks to add + - parameter months: number of months to add + - parameter years: number of years to add + - returns: the NSDate computed + */ + public func add(seconds: Int = 0, minutes: Int = 0, hours: Int = 0, days: Int = 0, weeks: Int = 0, months: Int = 0, years: Int = 0) -> Date { + let calendar = Calendar.current + let version = floor(NSFoundationVersionNumber) + + if version <= NSFoundationVersionNumber10_9_2 { + var component = DateComponents() + component.setValue(seconds, for: .second) + + var date : Date! = calendar.date(byAdding: component, to: self, wrappingComponents: false)! + component = DateComponents() + component.setValue(minutes, for: .minute) + date = calendar.date(byAdding: component, to: date, wrappingComponents: false)! - - /** - Date days - */ - public var days : Int { - get { - return getComponent(.day) - } + component = DateComponents() + component.setValue(hours, for: .hour) + date = calendar.date(byAdding: component, to: date, wrappingComponents: false)! + + component = DateComponents() + component.setValue(days, for: .day) + date = calendar.date(byAdding: component, to: date, wrappingComponents: false)! + + component = DateComponents() + component.setValue(weeks, for: .weekOfMonth) + date = calendar.date(byAdding: component, to: date, wrappingComponents: false)! + + component = DateComponents() + component.setValue(months, for: .month) + date = calendar.date(byAdding: component, to: date, wrappingComponents: false)! + + component = DateComponents() + component.setValue(years, for: .year) + date = calendar.date(byAdding: component, to: date, wrappingComponents: false)! + return date } - - /** - Date hours - */ - public var hours : Int { - - get { - return getComponent(.hour) - } + + var date : Date! = calendar.date(byAdding: Calendar.Component.second, value: seconds, to: self, wrappingComponents: false) + date = calendar.date(byAdding: Calendar.Component.minute, value: minutes, to: date, wrappingComponents: false) + date = calendar.date(byAdding: Calendar.Component.day, value: days, to: date, wrappingComponents: false) + date = calendar.date(byAdding: Calendar.Component.hour, value: hours, to: date, wrappingComponents: false) + date = calendar.date(byAdding: Calendar.Component.weekOfMonth, value: weeks, to: date, wrappingComponents: false) + date = calendar.date(byAdding: Calendar.Component.month, value: months, to: date, wrappingComponents: false) + date = calendar.date(byAdding: Calendar.Component.year, value: years, to: date, wrappingComponents: false) + return date + } + + /** + Returns a new NSDate object representing the date calculated by adding an amount of seconds to self date + + - parameter seconds: number of seconds to add + - returns: the NSDate computed + */ + public func addSeconds (_ seconds: Int) -> Date { + return add(seconds: seconds) + } + + /** + Returns a new NSDate object representing the date calculated by adding an amount of minutes to self date + + - parameter minutes: number of minutes to add + - returns: the NSDate computed + */ + public func addMinutes (_ minutes: Int) -> Date { + return add(minutes: minutes) + } + + /** + Returns a new NSDate object representing the date calculated by adding an amount of hours to self date + + - parameter hours: number of hours to add + - returns: the NSDate computed + */ + public func addHours(_ hours: Int) -> Date { + return add(hours: hours) + } + + /** + Returns a new NSDate object representing the date calculated by adding an amount of days to self date + + - parameter days: number of days to add + - returns: the NSDate computed + */ + public func addDays(_ days: Int) -> Date { + return add(days: days) + } + + /** + Returns a new NSDate object representing the date calculated by adding an amount of weeks to self date + + - parameter weeks: number of weeks to add + - returns: the NSDate computed + */ + public func addWeeks(_ weeks: Int) -> Date { + return add(weeks: weeks) + } + + + /** + Returns a new NSDate object representing the date calculated by adding an amount of months to self date + + - parameter months: number of months to add + - returns: the NSDate computed + */ + + public func addMonths(_ months: Int) -> Date { + return add(months: months) + } + + /** + Returns a new NSDate object representing the date calculated by adding an amount of years to self date + + - parameter years: number of year to add + - returns: the NSDate computed + */ + public func addYears(_ years: Int) -> Date { + return add(years: years) + } + + // MARK: Date comparison + + /** + Checks if self is after input NSDate + + - parameter date: NSDate to compare + - returns: True if self is after the input NSDate, false otherwise + */ + public func isAfter(_ date: Date) -> Bool{ + return (self.compare(date) == ComparisonResult.orderedDescending) + } + + /** + Checks if self is before input NSDate + + - parameter date: NSDate to compare + - returns: True if self is before the input NSDate, false otherwise + */ + public func isBefore(_ date: Date) -> Bool{ + return (self.compare(date) == ComparisonResult.orderedAscending) + } + + + // MARK: Getter + + /** + Date year + */ + public var year : Int { + get { + return getComponent(.year) } - - /** - Date minuts - */ - public var minutes : Int { - get { - return getComponent(.minute) - } + } + + /** + Date month + */ + public var month : Int { + get { + return getComponent(.month) } - - /** - Date seconds - */ - public var seconds : Int { - get { - return getComponent(.second) - } + } + + /** + Date weekday + */ + public var weekday : Int { + get { + return getComponent(.weekday) } - - /** - Returns the value of the NSDate component - - - parameter component: NSCalendarUnit - - returns: the value of the component - */ - - public func getComponent (_ component : NSCalendar.Unit) -> Int { - let calendar = Calendar.current - let components = (calendar as NSCalendar).components(component, from: self) - - return components.value(for: component) + } + + /** + Date weekMonth + */ + public var weekMonth : Int { + get { + return getComponent(.weekOfMonth) } -} + } -extension Date: Strideable { - public func distance(to other: Date) -> TimeInterval { - return other - self + + /** + Date days + */ + public var days : Int { + get { + return getComponent(.day) } - - public func advanced(by n: TimeInterval) -> Date { - return type(of: self).init(timeIntervalSinceReferenceDate: self.timeIntervalSinceReferenceDate + n) + } + + /** + Date hours + */ + public var hours : Int { + + get { + return getComponent(.hour) } -} -// MARK: Arithmetic + } -func +(date: Date, timeInterval: Int) -> Date { - return date + TimeInterval(timeInterval) -} + /** + Date minuts + */ + public var minutes : Int { + get { + return getComponent(.minute) + } + } -func -(date: Date, timeInterval: Int) -> Date { - return date - TimeInterval(timeInterval) -} + /** + Date seconds + */ + public var seconds : Int { + get { + return getComponent(.second) + } + } -func +=(date: inout Date, timeInterval: Int) { - date = date + timeInterval -} + /** + Returns the value of the NSDate component -func -=(date: inout Date, timeInterval: Int) { - date = date - timeInterval -} + - parameter component: NSCalendarUnit + - returns: the value of the component + */ -func +(date: Date, timeInterval: Double) -> Date { - return date.addingTimeInterval(TimeInterval(timeInterval)) + public func getComponent (_ component : Calendar.Component) -> Int { + let calendar = Calendar.current + return calendar.component(component, from: self) + } } -func -(date: Date, timeInterval: Double) -> Date { - return date.addingTimeInterval(TimeInterval(-timeInterval)) -} +extension Date: Strideable { + public func distance(to other: Date) -> TimeInterval { + return other - self + } -func +=(date: inout Date, timeInterval: Double) { - date = date + timeInterval + public func advanced(by n: TimeInterval) -> Date { + return type(of: self).init(timeIntervalSinceReferenceDate: self.timeIntervalSinceReferenceDate + n) + } } +// MARK: Arithmetic -func -=(date: inout Date, timeInterval: Double) { - date = date - timeInterval +public func +(date: Date, timeInterval: Int) -> Date { + return date + Double(timeInterval) } -func -(date: Date, otherDate: Date) -> TimeInterval { - return date.timeIntervalSince(otherDate) +public func -(date: Date, timeInterval: Int) -> Date { + return date - Double(timeInterval) } -public func ==(lhs: Date, rhs: Date) -> Bool { - return lhs.compare(rhs) == ComparisonResult.orderedSame +public func +=(date: inout Date, timeInterval: Int) { + date = date + timeInterval } -extension Date: Comparable { +public func -=(date: inout Date, timeInterval: Int) { + date = date - timeInterval } -public func <(lhs: Date, rhs: Date) -> Bool { - return lhs.compare(rhs) == ComparisonResult.orderedAscending +public func -(date: Date, otherDate: Date) -> TimeInterval { + return date.timeIntervalSince(otherDate) } From 2e17d0968c0af95f3af0c1c8340dc07e196a896e Mon Sep 17 00:00:00 2001 From: Andrew Ng Date: Thu, 29 Sep 2016 09:56:29 -0700 Subject: [PATCH 09/11] Updating my ExSwift branch with latest from my project --- ExSwift/Array.swift | 219 +++++++++++++++++++------------------------ ExSwift/String.swift | 2 +- 2 files changed, 99 insertions(+), 122 deletions(-) diff --git a/ExSwift/Array.swift b/ExSwift/Array.swift index 1244c9b..9958185 100644 --- a/ExSwift/Array.swift +++ b/ExSwift/Array.swift @@ -7,30 +7,10 @@ // import Foundation -fileprivate func < (lhs: T?, rhs: T?) -> Bool { - switch (lhs, rhs) { - case let (l?, r?): - return l < r - case (nil, _?): - return true - default: - return false - } -} - -fileprivate func >= (lhs: T?, rhs: T?) -> Bool { - switch (lhs, rhs) { - case let (l?, r?): - return l >= r - default: - return !(lhs < rhs) - } -} - -internal extension Array { +public extension Array { - fileprivate var indexesInterval: Range { return (0 ..< self.count) } + private var indexesInterval: Range { return (0 ..< self.count) } /** Checks if self contains a list of items. @@ -38,8 +18,25 @@ internal extension Array { - parameter items: Items to search for - returns: true if self contains all the items */ - func contains (_ items: Element...) -> Bool { - return items.all { (item: Element) -> Bool in self.indexOf(item) >= 0 } + public func contains (_ items: Element...) -> Bool { + + return items.all { (item: Element) -> Bool in + self.filter({$0 as? Element == item}).count > 0 + } + + //return self.filter({$0 as? T == obj}).count > 0 + +// +// print ("\nCHECK \(self) => \(items)") +// +// for item in items{ +// print("HMMM \(item) \(self.indexOf(item)) ") +// } +// +// +// return items.all { (item: Element) -> Bool in +// self.indexOf(item) >= 0 +// } } /** @@ -48,7 +45,7 @@ internal extension Array { - parameter values: Arrays to subtract - returns: Difference of self and the input arrays */ - func difference (_ values: [Element]...) -> [Element] { + public func difference (_ values: [Element]...) -> [Element] { var result = [Element]() @@ -77,7 +74,7 @@ internal extension Array { - parameter values: Arrays to intersect - returns: Array of unique values contained in all the dictionaries and self */ - func intersection (_ values: [U]...) -> Array { + public func intersection (_ values: [U]...) -> Array { var result = self var intersection = Array() @@ -111,7 +108,7 @@ internal extension Array { - parameter values: Arrays - returns: Union array of unique values */ - func union (_ values: [U]...) -> Array { + public func union (_ values: [U]...) -> Array { var result = self @@ -151,7 +148,7 @@ internal extension Array { - parameter item: The item to search for - returns: Matched item or nil */ - func find (_ item: U) -> Element? { + public func find (_ item: U) -> Element? { if let index: Int = indexOf(item) { return self[index] } @@ -165,7 +162,7 @@ internal extension Array { - parameter condition: A function which returns a boolean if an element satisfies a given condition or not. - returns: First matched item or nil */ - func find (_ condition: (Element) -> Bool) -> Element? { + public func find (_ condition: (Element) -> Bool) -> Element? { return takeFirst(condition) } @@ -175,7 +172,7 @@ internal extension Array { - parameter item: The item to search for - returns: Index of the matched item or nil */ - func indexOf (_ item: U) -> Int? { + public func indexOf (_ item: U) -> Int? { if item is Element { return self.index(where: { (object) -> Bool in return (object as! U) == item @@ -191,7 +188,7 @@ internal extension Array { - parameter item: The item to search for - returns: Index of the matched item or nil */ - func lastIndexOf (_ item: U) -> Int? { + public func lastIndexOf (_ item: U) -> Int? { if item is Element { for (index, value) in self.reversed().enumerated() { if value as! U == item { @@ -211,7 +208,7 @@ internal extension Array { - parameter index: - returns: Object at index in self */ - func get (_ index: Int) -> Element? { + public func get (_ index: Int) -> Element? { return index >= 0 && index < count ? self[index] : nil @@ -223,7 +220,7 @@ internal extension Array { - parameter range: - returns: Subarray in range */ - func get (_ range: Range) -> Array { + public func get (_ range: Range) -> Array { return Array(self[range]) @@ -236,7 +233,7 @@ internal extension Array { - parameter arrays: Arrays to zip - returns: Array of grouped elements */ - func zip (_ arrays: Any...) -> [[Any?]] { + public func zip (_ arrays: Any...) -> [[Any?]] { var result = [[Any?]]() @@ -267,7 +264,7 @@ internal extension Array { - parameter step: The number of elements to progress between each partition. Set to n if not supplied. - returns: Array partitioned into n element arrays, starting step elements apart. */ - func partition (_ n: Int, step: Int? = nil) -> [Array] { + public func partition (_ n: Int, step: Int? = nil) -> [Array] { var n = n var step = step @@ -278,7 +275,7 @@ internal extension Array { step = n } - if step < 1 { step = 1 } // Less than 1 results in an infinite loop. + if step! < 1 { step = 1 } // Less than 1 results in an infinite loop. if n < 1 { n = 0 } // Allow 0 if user wants [[],[],[]] for some reason. if n > count { return [[]] } @@ -299,7 +296,7 @@ internal extension Array { the last partition may less than n elements long. - returns: Array partitioned into n element arrays, starting step elements apart. */ - func partition (_ n: Int, step: Int? = nil, pad: Array?) -> [Array] { + public func partition (_ n: Int, step: Int? = nil, pad: Array?) -> [Array] { var result = [Array]() var n = n var step = step @@ -310,7 +307,7 @@ internal extension Array { } // Less than 1 results in an infinite loop. - if step < 1 { + if step! < 1 { step = 1 } @@ -348,7 +345,7 @@ internal extension Array { - parameter step: The number of elements to progress between each partition. Set to n if not supplied. - returns: Array partitioned into n element arrays, starting step elements apart. */ - func partitionAll (_ n: Int, step: Int? = nil) -> [Array] { + public func partitionAll (_ n: Int, step: Int? = nil) -> [Array] { var result = [Array]() var n = n var step = step @@ -358,7 +355,7 @@ internal extension Array { step = n } - if step < 1 { step = 1 } // Less than 1 results in an infinite loop. + if step! < 1 { step = 1 } // Less than 1 results in an infinite loop. if n < 1 { n = 0 } // Allow 0 if user wants [[],[],[]] for some reason. for i in stride(from: 0, through: count, by: step!) { @@ -374,7 +371,7 @@ internal extension Array { - parameter cond: Function which takes an element and produces an equatable result. - returns: Array partitioned in order, splitting via results of cond. */ - func partitionBy (_ cond: (Element) -> Element) -> [Array] { + public func partitionBy (_ cond: (Element) -> Element) -> [Array] { var result = [Array]() var lastValue: Element? = nil @@ -396,7 +393,7 @@ internal extension Array { /** Randomly rearranges the elements of self using the Fisher-Yates shuffle */ - mutating func shuffle () { + public mutating func shuffle () { for i in (1..= 1; i -= 1 { @@ -411,7 +408,7 @@ internal extension Array { - returns: Shuffled copy of self */ - func shuffled () -> Array { + public func shuffled () -> Array { var shuffled = self shuffled.shuffle() @@ -425,7 +422,7 @@ internal extension Array { - parameter n: Length - returns: Random subarray of length n */ - func sample (size n: Int = 1) -> Array { + public func sample (size n: Int = 1) -> Array { if n >= count { return self } @@ -439,7 +436,7 @@ internal extension Array { - returns: Max value */ - func max () -> U { + public func max () -> U { return map { return $0 as! U @@ -452,7 +449,7 @@ internal extension Array { - returns: Min value */ - func min () -> U { + public func min () -> U { return map { return $0 as! U @@ -465,7 +462,7 @@ internal extension Array { - returns: Max value in terms of call(value) */ - func maxBy (_ call: (Element) -> (U)) -> Element? { + public func maxBy (_ call: (Element) -> (U)) -> Element? { if let firstValue = self.first { var maxElement: Element = firstValue @@ -490,7 +487,7 @@ internal extension Array { - returns: Min value in terms of call(value) */ - func minBy (_ call: (Element) -> (U)) -> Element? { + public func minBy (_ call: (Element) -> (U)) -> Element? { if let firstValue = self.first { var minElement: Element = firstValue @@ -515,7 +512,7 @@ internal extension Array { - parameter call: Function to call for each element */ - func each (_ call: (Element) -> ()) { + public func each (_ call: (Element) -> ()) { for item in self { call(item) @@ -528,7 +525,7 @@ internal extension Array { - parameter call: Function to call for each element */ - func each (_ call: (Int, Element) -> ()) { + public func each (_ call: (Int, Element) -> ()) { for (index, item) in self.enumerated() { call(index, item) @@ -541,7 +538,7 @@ internal extension Array { - parameter call: Function to call for each element */ - @available(*, unavailable, message: "use 'reverse().each' instead") func eachRight (_ call: (Element) -> ()) { + @available(*, unavailable, message: "use 'reverse().each' instead") public func eachRight (_ call: (Element) -> ()) { reversed().each(call) } @@ -550,7 +547,7 @@ internal extension Array { - parameter call: Function to call for each element */ - @available(*, unavailable, message: "use 'reverse().each' instead") func eachRight (_ call: (Int, Element) -> ()) { + @available(*, unavailable, message: "use 'reverse().each' instead") public func eachRight (_ call: (Int, Element) -> ()) { for (index, item) in reversed().enumerated() { call(count - index - 1, item) } @@ -562,7 +559,7 @@ internal extension Array { - parameter test: Function to call for each element - returns: true if test returns true for any element of self */ - func any (_ test: (Element) -> Bool) -> Bool { + public func any (_ test: (Element) -> Bool) -> Bool { for item in self { if test(item) { return true @@ -578,7 +575,7 @@ internal extension Array { - parameter test: Function to call for each element - returns: True if test returns true for all the elements in self */ - func all (_ test: (Element) -> Bool) -> Bool { + public func all (_ test: (Element) -> Bool) -> Bool { for item in self { if !test(item) { return false @@ -594,7 +591,7 @@ internal extension Array { - parameter exclude: Function invoked to test elements for the exclusion from the array - returns: Filtered array */ - func reject (_ exclude: ((Element) -> Bool)) -> Array { + public func reject (_ exclude: (Element) -> Bool) -> Array { return filter { return !exclude($0) } @@ -606,7 +603,7 @@ internal extension Array { - parameter n: Number of elements to take - returns: First n elements */ - func take (_ n: Int) -> Array { + public func take (_ n: Int) -> Array { return Array(self[0.. Bool) -> Array { + public func takeWhile (_ condition: (Element) -> Bool) -> Array { var lastTrue = -1 @@ -638,7 +635,7 @@ internal extension Array { - parameter condition: A function which returns a boolean if an element satisfies a given condition or not. - returns: The first element in the array to meet the condition */ - func takeFirst (_ condition: (Element) -> Bool) -> Element? { + public func takeFirst (_ condition: (Element) -> Bool) -> Element? { for value in self { if condition(value) { @@ -656,7 +653,7 @@ internal extension Array { - parameter n: Number of elements to take - returns: Last n elements */ - func tail (_ n: Int) -> Array { + public func tail (_ n: Int) -> Array { return Array(self[(count - n).. Array { + public func skip (_ n: Int) -> Array { return n > count ? [] : Array(self[Int(n).. Bool) -> Array { + public func skipWhile (_ condition: (Element) -> Bool) -> Array { var lastTrue = -1 @@ -701,7 +698,7 @@ internal extension Array { - returns: Array of unique values */ - func unique () -> [Element] { + public func unique () -> [Element] { var result = [Element]() for item in self { @@ -719,7 +716,7 @@ internal extension Array { - parameter call: The closure to use to determine uniqueness - returns: The set of elements for which call(element) is unique */ - func uniqueBy (_ call: (Element) -> (Element)) -> [Element] { + public func uniqueBy (_ call: (Element) -> (Element)) -> [Element] { var result: [Element] = [] var uniqueItems: [Element] = [] @@ -740,7 +737,7 @@ internal extension Array { - parameter length: The length of each permutation - returns: All permutations of a given length within an array */ - func permutation (_ length: Int) -> [[Element]] { + public func permutation (_ length: Int) -> [[Element]] { if length < 0 || length > self.count { return [] } else if length == 0 { @@ -761,12 +758,12 @@ internal extension Array { Recursive helper method where all of the permutation-generating work is done This is Heap's algorithm */ - fileprivate func permutationHelper(_ n: Int, array: inout [Element], endArray: inout [[Element]]) -> [[Element]] { + private func permutationHelper(_ n: Int, array: inout [Element], endArray: inout [[Element]]) -> [[Element]] { if n == 1 { endArray += [array] } for i in 0 ..< n { - permutationHelper(n - 1, array: &array, endArray: &endArray) + _ = permutationHelper(n - 1, array: &array, endArray: &endArray) let j = n % 2 == 0 ? i : 0; //(array[j], array[n - 1]) = (array[n - 1], array[j]) let temp: Element = array[j] @@ -784,7 +781,7 @@ internal extension Array { - parameter groupingFunction: - returns: Grouped dictionary */ - func groupBy (groupingFunction group: (Element) -> U) -> [U: Array] { + public func groupBy (groupingFunction group: (Element) -> U) -> [U: Array] { var result = [U: Array]() @@ -810,7 +807,7 @@ internal extension Array { - parameter groupingFunction: - returns: Grouped dictionary */ - func countBy (groupingFunction group: (Element) -> U) -> [U: Int] { + public func countBy (groupingFunction group: (Element) -> U) -> [U: Int] { var result = [U: Int]() @@ -833,7 +830,7 @@ internal extension Array { - parameter length: - returns: Combinations */ - func repeatedCombination (_ length: Int) -> [[Element]] { + public func repeatedCombination (_ length: Int) -> [[Element]] { if length < 0 { return [] } @@ -872,7 +869,7 @@ internal extension Array { - parameter length: - returns: Combinations */ - func combination (_ length: Int) -> [[Element]] { + public func combination (_ length: Int) -> [[Element]] { if length < 0 || length > self.count { return [] } @@ -907,7 +904,7 @@ internal extension Array { - parameter length: The length of each permutations :returns All of the permutations of this array of a given length, allowing repeats */ - func repeatedPermutation(_ length: Int) -> [[Element]] { + public func repeatedPermutation(_ length: Int) -> [[Element]] { if length < 1 { return [] } @@ -916,7 +913,7 @@ internal extension Array { return permutationIndexes.map({ $0.map({ i in self[i] }) }) } - fileprivate func repeatedPermutationHelper(_ seed: [Int], length: Int, arrayLength: Int, permutationIndexes: inout [[Int]]) { + private func repeatedPermutationHelper(_ seed: [Int], length: Int, arrayLength: Int, permutationIndexes: inout [[Int]]) { if seed.count == length { permutationIndexes.append(seed) return @@ -934,7 +931,7 @@ internal extension Array { - parameter test: Function to call for each element - returns: the number of elements meeting the condition */ - func countWhere (_ test: (Element) -> Bool) -> Int { + public func countWhere (_ test: (Element) -> Bool) -> Int { var result = 0 @@ -947,7 +944,7 @@ internal extension Array { return result } - func eachIndex (_ call: @escaping (Int) -> ()) -> () { + public func eachIndex (_ call: (Int) -> ()) -> () { (0.. [[Element]] { // () -> [[U]] { + public func transposition (_ array: [[Element]]) -> [[Element]] { // () -> [[U]] { let maxWidth: Int = array.map({ $0.count }).max() var transposition = [[Element]](repeating: [], count: maxWidth) @@ -977,7 +974,7 @@ internal extension Array { - parameter object: The object to replace each element with */ - mutating func fill (_ object: Element) -> () { + public mutating func fill (_ object: Element) -> () { (0.. (_ separator: C) -> C? { + public func implode (_ separator: C) -> C? { if Element.self is C.Type { if let joined = unsafeBitCast(self, to: [C].self).joined(separator: separator) as? C { return joined @@ -1009,7 +1006,7 @@ internal extension Array { - parameter mapFunction: - returns: Mapped array */ - func mapFilter (mapFunction map: (Element) -> (V)?) -> [V] { + public func mapFilter (mapFunction map: (Element) -> (V)?) -> [V] { var mapped = [V]() @@ -1031,7 +1028,7 @@ internal extension Array { - parameter mapFunction: - returns: Accumulated value and mapped array */ - func mapAccum (_ initial: U, mapFunction map: (U, Element) -> (U, V)) -> (U, [V]) { + public func mapAccum (_ initial: U, mapFunction map: (U, Element) -> (U, V)) -> (U, [V]) { var mapped = [V]() var acc = initial @@ -1047,7 +1044,7 @@ internal extension Array { /** self.reduce with initial value self.first() */ - func reduce (_ combine: (Element, Element) -> Element) -> Element? { + public func reduce (_ combine: (Element, Element) -> Element) -> Element? { if let firstElement = first { return skip(1).reduce(firstElement, combine) } @@ -1058,14 +1055,14 @@ internal extension Array { /** self.reduce from right to left */ - @available(*, unavailable, message: "use 'reverse().reduce' instead") func reduceRight (_ initial: U, combine: (U, Element) -> U) -> U { + @available(*, unavailable, message: "use 'reverse().reduce' instead") public func reduceRight (_ initial: U, combine: (U, Element) -> U) -> U { return reversed().reduce(initial, combine) } /** self.reduceRight with initial value self.last() */ - @available(*, unavailable, message: "use 'reverse().reduce' instead") func reduceRight (_ combine: (Element, Element) -> Element) -> Element? { + @available(*, unavailable, message: "use 'reverse().reduce' instead") public func reduceRight (_ combine: (Element, Element) -> Element) -> Element? { return reversed().reduce(combine) } @@ -1075,7 +1072,7 @@ internal extension Array { - parameter indexes: Indexes of the elements to get - returns: Array with the elements at indexes */ - func at (_ indexes: Int...) -> Array { + public func at (_ indexes: Int...) -> Array { return indexes.map { self.get($0)! } } @@ -1085,7 +1082,7 @@ internal extension Array { - parameter keySelector: - returns: A dictionary */ - func toDictionary (_ keySelector:(Element) -> U) -> [U: Element] { + public func toDictionary (_ keySelector:(Element) -> U) -> [U: Element] { var result: [U: Element] = [:] for item in self { result[keySelector(item)] = item @@ -1100,7 +1097,7 @@ internal extension Array { - parameter transform: - returns: A dictionary */ - func toDictionary (_ transform: (Element) -> (key: K, value: V)?) -> [K: V] { + public func toDictionary (_ transform: (Element) -> (key: K, value: V)?) -> [K: V] { var result: [K: V] = [:] for item in self { if let entry = transform(item) { @@ -1116,7 +1113,7 @@ internal extension Array { - returns: Flattened array */ - func flatten () -> [OutType] { + public func flatten () -> [OutType] { var result = [OutType]() let mirror = Mirror(reflecting: self) if let mirrorChildrenCollection = AnyRandomAccessCollection(mirror.children) { @@ -1131,12 +1128,12 @@ internal extension Array { } /** - Flattens a nested Array self to an array of AnyObject. + Flattens a nested Array self to an array of Any. - returns: Flattened array */ - func flattenAny () -> [AnyObject] { - var result = [AnyObject]() + public func flattenAny () -> [Any] { + var result = [Any]() for item in self { if let array = item as? NSArray { @@ -1155,7 +1152,7 @@ internal extension Array { - parameter isOrderedBefore: Comparison function. - returns: An array that is sorted according to the given function */ - @available(*, unavailable, message: "use 'sort' instead") func sortBy (_ isOrderedBefore: (Element, Element) -> Bool) -> [Element] { + @available(*, unavailable, message: "use 'sort' instead") public func sortBy (_ isOrderedBefore: (Element, Element) -> Bool) -> [Element] { return sorted(by: isOrderedBefore) } @@ -1165,7 +1162,7 @@ internal extension Array { - parameter n: the number of times to cycle through - parameter block: the block to run for each element in each cycle */ - func cycle (_ n: Int? = nil, block: (Element) -> ()) { + public func cycle (_ n: Int? = nil, block: (Element) -> ()) { var cyclesRun = 0 while true { if let n = n { @@ -1190,7 +1187,7 @@ internal extension Array { - parameter block: the block to run each time - returns: the min element, or nil if there are no items for which the block returns true */ - func bSearch (_ block: (Element) -> (Bool)) -> Element? { + public func bSearch (_ block: (Element) -> (Bool)) -> Element? { if count == 0 { return nil } @@ -1224,7 +1221,7 @@ internal extension Array { - parameter block: the block to run each time - returns: an item (there could be multiple matches) for which the block returns true */ - /*func bSearch (block: (Element) -> (Int)) -> Element? { + /*public func bSearch (block: (Element) -> (Int)) -> Element? { let match = bSearch { item in block(item) >= 0 } @@ -1241,7 +1238,7 @@ internal extension Array { - parameter block: the block to use to sort by - returns: an array sorted by that block, in ascending order */ - func sortUsing (_ block: ((Element) -> U)) -> [Element] { + public func sortUsing (_ block: ((Element) -> U)) -> [Element] { return self.sorted(by: { block($0.0) < block($0.1) }) } @@ -1250,7 +1247,7 @@ internal extension Array { - returns: The removed element */ - mutating func pop () -> Element? { + public mutating func pop () -> Element? { if self.isEmpty { return nil @@ -1265,7 +1262,7 @@ internal extension Array { - parameter newElement: Element to append */ - mutating func push (_ newElement: Element) { + public mutating func push (_ newElement: Element) { return append(newElement) } @@ -1274,7 +1271,7 @@ internal extension Array { - returns: The removed element */ - mutating func shift () -> Element? { + public mutating func shift () -> Element? { if self.isEmpty { return nil @@ -1289,7 +1286,7 @@ internal extension Array { - parameter newElement: Object to prepend */ - mutating func unshift (_ newElement: Element) { + public mutating func unshift (_ newElement: Element) { insert(newElement, at: 0) } @@ -1299,7 +1296,7 @@ internal extension Array { - parameter newArray: Array to insert - parameter atIndex: Where to insert the array */ - mutating func insert (_ newArray: Array, atIndex: Int) { + public mutating func insert (_ newArray: Array, atIndex: Int) { self = take(atIndex) + newArray + skip(atIndex) } @@ -1308,7 +1305,7 @@ internal extension Array { - parameter element: Element to remove */ - mutating func remove (_ element: U) { + public mutating func remove (_ element: U) { let anotherSelf = self removeAll(keepingCapacity: true) @@ -1327,7 +1324,7 @@ internal extension Array { - parameter range: - returns: Array of values */ - @available(*, unavailable, message: "use the '[U](range)' constructor") func range (_ range: Range) -> [U] { + @available(*, unavailable, message: "use the '[U](range)' constructor") public func range (_ range: CountableRange) -> [U] { return [U](range) } @@ -1348,26 +1345,6 @@ internal extension Array { return Array(self[start ..< end] as ArraySlice) } - - /** - Returns a subarray whose items are in the given interval in self. - - - parameter interval: Interval of indexes of the subarray elements - - returns: Subarray or nil if the index is out of bounds - */ - subscript (interval: Range) -> Array { - return self[rangeAsArray: interval.start ..< interval.end] - } - - /** - Returns a subarray whose items are in the given interval in self. - - - parameter interval: Interval of indexes of the subarray elements - - returns: Subarray or nil if the index is out of bounds - */ - subscript (interval: ClosedRange) -> Array { - return self[rangeAsArray: interval.start ..< (interval.end + 1)] - } /** Creates an array with the elements at indexes in the given list of integers. diff --git a/ExSwift/String.swift b/ExSwift/String.swift index f37e4cb..03a093e 100644 --- a/ExSwift/String.swift +++ b/ExSwift/String.swift @@ -18,7 +18,7 @@ public extension String { /** self.capitalizedString shorthand */ - var capitalized: String { return capitalized } + var capitalized: String { return self.capitalized } /** Returns the substring in the given range From 1abdc5c60baea8b579e7220cd36946328299b3da Mon Sep 17 00:00:00 2001 From: Mattes Groeger Date: Thu, 15 Dec 2016 11:59:31 +0100 Subject: [PATCH 10/11] Fix warnings for result not being used --- ExSwift/Sequence.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ExSwift/Sequence.swift b/ExSwift/Sequence.swift index 2149ae7..60928a6 100644 --- a/ExSwift/Sequence.swift +++ b/ExSwift/Sequence.swift @@ -45,7 +45,7 @@ internal extension AnySequence { func get (_ index: Int) -> Element? { let generator = self.makeIterator() for _ in 0..<(index - 1) { - generator.next() + _ = generator.next() } return generator.next() } @@ -88,7 +88,7 @@ internal extension AnySequence { func skip (_ n: Int) -> AnySequence { let generator = self.makeIterator() for _ in 0.. Date: Mon, 24 Apr 2017 16:09:31 +0300 Subject: [PATCH 11/11] Swift 3 ambiguity + recurse call --- ExSwift/String.swift | 5 ----- 1 file changed, 5 deletions(-) diff --git a/ExSwift/String.swift b/ExSwift/String.swift index 03a093e..51bc9da 100644 --- a/ExSwift/String.swift +++ b/ExSwift/String.swift @@ -15,11 +15,6 @@ public extension String { */ var length: Int { return self.characters.count } - /** - self.capitalizedString shorthand - */ - var capitalized: String { return self.capitalized } - /** Returns the substring in the given range