From 30850ccd6410c6733cbc5011c28569662029e990 Mon Sep 17 00:00:00 2001 From: pNre Date: Tue, 9 Jun 2015 21:22:54 +0200 Subject: [PATCH 1/4] 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 2/4] 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 df9cca73ade347e4f71d83d9bfa576c78ef010fe Mon Sep 17 00:00:00 2001 From: Gabriele Date: Sat, 22 Aug 2015 21:33:50 +0200 Subject: [PATCH 3/4] Fix generics to Element, build in Xcode 7 beta 4 --- ExSwift/Sequence.swift | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/ExSwift/Sequence.swift b/ExSwift/Sequence.swift index 1b2c043..66fe78c 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 { + func filter(include: (Element) -> Bool) -> AnySequence { return AnySequence(lazy(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) } From 7cbc90d676a72e417180aa8b5e35e9dfbe4dd5a6 Mon Sep 17 00:00:00 2001 From: Gabriele Pongelli Date: Sun, 23 Aug 2015 18:06:48 +0200 Subject: [PATCH 4/4] Fixed all T to Element; commented methods that I can't fix to Swift 2 --- ExSwift/Array.swift | 104 +++++++++++++++++++++--------------------- ExSwift/ExSwift.swift | 8 ++-- ExSwift/NSArray.swift | 14 +++--- ExSwift/NSDate.swift | 2 +- ExSwift/Range.swift | 10 ++-- 5 files changed, 70 insertions(+), 68 deletions(-) diff --git a/ExSwift/Array.swift b/ExSwift/Array.swift index 5bdbeac..431fddf 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] } @@ -221,16 +221,18 @@ internal extension Array { var result = [[Any?]]() // Gets the longest sequence - let max = arrays.map { (element: Any) -> Int in - return reflect(element).count - }.max() as Int + let arrayCount = arrays.map({ (element : Any) -> Int64 in + let mirrored = Mirror(reflecting: element) + return mirrored.children.count + }) - for i in 0.. Any? in - let (_, mirror) = reflect(element)[i] - return mirror.value + //let (_, mirror) = Mirror(reflecting: element).children[i] + return Mirror(reflecting: element).children }) } @@ -346,12 +348,12 @@ 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) -> 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 @@ -439,7 +441,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.. () -> [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,15 +692,15 @@ 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] { - var result: [Element] = [] - var uniqueItems: [T] = [] + func uniqueBy (call: (Element) -> (Element)) -> [Element] { + var result = [Element]() + 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) } } @@ -711,16 +713,16 @@ internal extension 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 +734,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 +742,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 +880,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 +931,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)) } @@ -1083,16 +1085,16 @@ internal extension Array { - returns: Flattened array */ - func flatten () -> [OutType] { + /*func flatten () -> [OutType] { var result = [OutType]() - let reflection = reflect(self) + let reflection = Mirror(reflecting: 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 +1131,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 +1156,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 +1190,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 } @@ -1205,7 +1207,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) }) } @@ -1310,7 +1312,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) } /** @@ -1351,28 +1353,28 @@ internal extension Array { /** 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..55361d0 100644 --- a/ExSwift/ExSwift.swift +++ b/ExSwift/ExSwift.swift @@ -243,9 +243,9 @@ 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 = reflect(object) + let reflection = Mirror(reflecting: object) // object has an Objective-C type if let obj = object as? T { @@ -264,7 +264,7 @@ extension ExSwift { // object is a native Swift array // recursively convert each item - (0.. () -> [OutType] { + /*func cast () -> [OutType] { var result = [OutType]() for item : AnyObject in self { @@ -23,7 +23,7 @@ public extension NSArray { } return result - } + }*/ /** Flattens a multidimensional NSArray to an OutType[] array @@ -31,16 +31,16 @@ public extension NSArray { - returns: Flattened array */ - func flatten () -> [OutType] { + /*func flatten () -> [OutType] { var result = [OutType]() - let reflection = reflect(self) + let reflection = Mirror(reflecting: 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) }