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 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 @@ + + + + { return HalfOpenInterval(0, self.count) } + private var indexesInterval: Range { return (0 ..< self.count) } /** Checks if self contains a list of items. - :param: items Items to search for - :returns: true if self contains all the items + - parameter items: Items to search for + - returns: true if self contains all the items */ - func contains (items: T...) -> Bool { - return items.all { self.indexOf($0) >= 0 } + public func contains (_ items: Element...) -> Bool { + + return items.all { (item: Element) -> Bool in + self.filter({$0 as? Element == item}).count > 0 + } + + //return self.filter({$0 as? T == obj}).count > 0 + +// +// print ("\nCHECK \(self) => \(items)") +// +// for item in items{ +// print("HMMM \(item) \(self.indexOf(item)) ") +// } +// +// +// return items.all { (item: Element) -> Bool in +// self.indexOf(item) >= 0 +// } } /** 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] { + public 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 @@ -54,15 +71,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 { + public func intersection (_ values: [U]...) -> Array { var result = self var intersection = Array() - for (i, value) in enumerate(values) { + for (i, value) in values.enumerated() { // the intersection is computed by intersecting a couple per loop: // self n values[0], (self n values[0]) n values[1], ... @@ -88,10 +105,10 @@ 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 { + public func union (_ values: [U]...) -> Array { var result = self @@ -110,29 +127,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) { + public func find (_ item: U) -> Element? { + if let index: Int = indexOf(item) { return self[index] } @@ -140,40 +157,26 @@ 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? { + public func find (_ condition: (Element) -> Bool) -> Element? { return takeFirst(condition) } /** 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? { + public 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.index(where: { (object) -> Bool in + return (object as! U) == item + }) } return nil @@ -182,12 +185,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? { + public func lastIndexOf (_ item: U) -> Int? { if item is Element { - for (index, value) in enumerate(lazy(self).reverse()) { + for (index, value) in self.reversed().enumerated() { if value as! U == item { return count - 1 - index } @@ -202,10 +205,10 @@ 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? { + public func get (_ index: Int) -> Element? { return index >= 0 && index < count ? self[index] : nil @@ -214,12 +217,12 @@ 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 { + public func get (_ range: Range) -> Array { - return self[rangeAsArray: range] + return Array(self[range]) } @@ -227,24 +230,25 @@ 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?]] { + public func zip (_ arrays: Any...) -> [[Any?]] { var result = [[Any?]]() // Gets the longest sequence let max = arrays.map { (element: Any) -> Int in - return reflect(element).count + return Int(Mirror(reflecting: element).children.count) }.max() as Int for i in 0.. Any? in - let (_, mirror) = reflect(element)[i] - return mirror.value + // let (_, mirror) = reflect(element)[i] + // return mirror.value + return Mirror(reflecting: element).children }) } @@ -256,11 +260,14 @@ 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] { + public func partition (_ n: Int, step: Int? = nil) -> [Array] { + var n = n + var step = step + var result = [Array]() // If no step is supplied move n each step. @@ -268,12 +275,12 @@ internal extension Array { step = n } - if step < 1 { step = 1 } // Less than 1 results in an infinite loop. + if step! < 1 { step = 1 } // Less than 1 results in an infinite loop. if n < 1 { n = 0 } // Allow 0 if user wants [[],[],[]] for some reason. if n > count { return [[]] } for i in stride(from: 0, through: count - n, by: step!) { - result += [self[i..<(i + n)]] + result += [Array(self[i..<(i + n)])] } return result @@ -282,15 +289,17 @@ 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] { + public func partition (_ n: Int, step: Int? = nil, pad: Array?) -> [Array] { var result = [Array]() + var n = n + var step = step // If no step is supplied move n each step. if step == nil { @@ -298,7 +307,7 @@ internal extension Array { } // Less than 1 results in an infinite loop. - if step < 1 { + if step! < 1 { step = 1 } @@ -307,14 +316,14 @@ internal extension Array { n = 0 } - for i in stride(from: 0, to: count, by: step!) { + for i in stride(from: 0, through: count, by: step!) { var end = i + n if end > count { end = count } - - result += [self[i.. [Array] { + public func partitionAll (_ n: Int, step: Int? = nil) -> [Array] { var result = [Array]() + var n = n + var step = step // If no step is supplied move n each step. if step == nil { step = n } - if step < 1 { step = 1 } // Less than 1 results in an infinite loop. + if step! < 1 { step = 1 } // Less than 1 results in an infinite loop. if n < 1 { n = 0 } // Allow 0 if user wants [[],[],[]] for some reason. - for i in stride(from: 0, to: count, by: step!) { - result += [self[i..<(i + n)]] + for i in stride(from: 0, through: count, by: step!) { + result += [Array(self[i..<(i + n)])] } return result @@ -357,15 +368,15 @@ 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] { + public 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 @@ -382,9 +393,10 @@ internal extension Array { /** Randomly rearranges the elements of self using the Fisher-Yates shuffle */ - mutating func shuffle () { + public mutating func shuffle () { - for var i = self.count - 1; i >= 1; i-- { + for i in (1..= 1; i -= 1 { let j = Int.random(max: i) swap(&self[i], &self[j]) } @@ -394,9 +406,9 @@ 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 { + public func shuffled () -> Array { var shuffled = self shuffled.shuffle() @@ -407,53 +419,53 @@ 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 { + public func sample (size n: Int = 1) -> Array { if n >= count { return self } let index = Int.random(max: count - n) - return self[index..<(n + index)] + return Array(self[index..<(n + index)]) } /** Max value in the current array (if Array.Element implements the Comparable protocol). - :returns: Max value + - returns: Max value */ - func max () -> U { + public func max () -> U { - return maxElement(map { + return map { return $0 as! U - }) + }.max()! } /** Min value in the current array (if Array.Element implements the Comparable protocol). - :returns: Min value + - returns: Min value */ - func min () -> U { + public func min () -> U { - return minElement(map { + return map { return $0 as! U - }) + }.min()! } /** 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? { + public 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? { + public func minBy (_ 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.. ()) { + public func each (_ call: (Element) -> ()) { for item in self { call(item) @@ -511,11 +523,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) -> ()) { + public func each (_ call: (Int, Element) -> ()) { - for (index, item) in enumerate(self) { + for (index, item) in self.enumerated() { call(index, item) } @@ -524,19 +536,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) -> ()) { - reverse().each(call) + @available(*, unavailable, message: "use 'reverse().each' instead") public func eachRight (_ call: (Element) -> ()) { + reversed().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") public func eachRight (_ call: (Int, Element) -> ()) { + for (index, item) in reversed().enumerated() { call(count - index - 1, item) } } @@ -544,10 +556,10 @@ 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 { + public func any (_ test: (Element) -> Bool) -> Bool { for item in self { if test(item) { return true @@ -560,10 +572,10 @@ 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 { + public func all (_ test: (Element) -> Bool) -> Bool { for item in self { if !test(item) { return false @@ -576,10 +588,10 @@ 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 { + public func reject (_ exclude: (Element) -> Bool) -> Array { return filter { return !exclude($0) } @@ -588,24 +600,24 @@ 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.. Array { + return Array(self[0.. Bool) -> Array { + public func takeWhile (_ condition: (Element) -> Bool) -> Array { var lastTrue = -1 - for (index, value) in enumerate(self) { + for (index, value) in self.enumerated() { if condition(value) { lastTrue = index } else { @@ -620,10 +632,10 @@ 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? { + public func takeFirst (_ condition: (Element) -> Bool) -> Element? { for value in self { if condition(value) { @@ -638,38 +650,38 @@ 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 { + public func tail (_ n: Int) -> Array { - return self[(count - n).. Array { + public func skip (_ n: Int) -> Array { - return n > count ? [] : self[Int(n).. count ? [] : Array(self[Int(n).. Bool) -> Array { + public func skipWhile (_ condition: (Element) -> Bool) -> Array { var lastTrue = -1 - for (index, value) in enumerate(self) { + for (index, value) in self.enumerated() { if condition(value) { lastTrue = index } else { @@ -684,14 +696,14 @@ 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]() + public 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) } } @@ -701,41 +713,40 @@ 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] { + public func uniqueBy (_ call: (Element) -> (Element)) -> [Element] { var result: [Element] = [] - var uniqueItems: [T] = [] + var uniqueItems: [Element] = [] for item in self { - var callResult: T = call(item) + let callResult: Element = call(item as! Element) if !uniqueItems.contains(callResult) { uniqueItems.append(callResult) - result.append(item) + result.append(item as! Element) } } return result } - + /** Returns all permutations of a given length within an array - :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 + public 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) } @@ -747,15 +758,15 @@ 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, array: inout [Element], endArray: inout [[Element]]) -> [[Element]] { if n == 1 { endArray += [array] } - for var i = 0; i < n; i++ { - permutationHelper(n - 1, array: &array, endArray: &endArray) - var j = n % 2 == 0 ? i : 0; + for i in 0 ..< n { + _ = permutationHelper(n - 1, array: &array, endArray: &endArray) + let j = n % 2 == 0 ? i : 0; //(array[j], array[n - 1]) = (array[n - 1], array[j]) - var temp: T = array[j] + let temp: Element = array[j] array[j] = array[n - 1] array[n - 1] = temp } @@ -767,10 +778,10 @@ 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] { + public func groupBy (groupingFunction group: (Element) -> U) -> [U: Array] { var result = [U: Array]() @@ -793,10 +804,10 @@ 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] { + public func countBy (groupingFunction group: (Element) -> U) -> [U: Int] { var result = [U: Int]() @@ -804,7 +815,7 @@ internal extension Array { let groupKey = group(item) if result.has(groupKey) { - result[groupKey]!++ + result[groupKey]! += 1 } else { result[groupKey] = 1 } @@ -816,19 +827,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]] { + public 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 { @@ -837,12 +850,12 @@ internal extension Array { combinations.append(combination) var i = indexes.count - 1 while i >= 0 && indexes[i] == self.count - 1 { - i-- + i -= 1 } if i < 0 { break } - indexes[i]++ + indexes[i] += 1 (i+1).upTo(indexes.count - 1) { j in indexes[j] = indexes[i] } @@ -853,16 +866,16 @@ 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]] { + public func combination (_ length: Int) -> [[Element]] { if length < 0 || length > self.count { return [] } var indexes: [Int] = (0..= 0 && indexes[i] == i + offset { - i-- + i -= 1 } if i < 0 { break } - i++ - var start = indexes[i-1] + 1 + i += 1 + let start = indexes[i-1] + 1 for j in (i-1).. [[T]] { + public func repeatedPermutation(_ length: Int) -> [[Element]] { if length < 1 { return [] } @@ -900,7 +913,7 @@ internal extension Array { return permutationIndexes.map({ $0.map({ i in self[i] }) }) } - private func repeatedPermutationHelper(seed: [Int], length: Int, arrayLength: Int, inout permutationIndexes: [[Int]]) { + private func repeatedPermutationHelper(_ seed: [Int], length: Int, arrayLength: Int, permutationIndexes: inout [[Int]]) { if seed.count == length { permutationIndexes.append(seed) return @@ -915,23 +928,23 @@ 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 { + public func countWhere (_ test: (Element) -> Bool) -> Int { var result = 0 for item in self { if test(item) { - result++ + result += 1 } } return result } - func eachIndex (call: (Int) -> ()) -> () { + public func eachIndex (_ call: (Int) -> ()) -> () { (0.. [[T]] { // () -> [[U]] { - var maxWidth: Int = array.map({ $0.count }).max() - var transposition = [[T]](count: maxWidth, repeatedValue: []) + public func transposition (_ array: [[Element]]) -> [[Element]] { // () -> [[U]] { + let maxWidth: Int = array.map({ $0.count }).max() + var transposition = [[Element]](repeating: [], count: maxWidth) (0.. () { + public mutating func fill (_ object: Element) -> () { (0.. (separator: C) -> C? { + public func implode (_ separator: C) -> C? { if Element.self is C.Type { - return Swift.join(separator, unsafeBitCast(self, [C].self)) + if let joined = unsafeBitCast(self, to: [C].self).joined(separator: separator) as? C { + return joined + } else { + return nil + } } return nil @@ -986,10 +1003,10 @@ 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] { + public func mapFilter (mapFunction map: (Element) -> (V)?) -> [V] { var mapped = [V]() @@ -1007,11 +1024,11 @@ 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]) { + public func mapAccum (_ initial: U, mapFunction map: (U, Element) -> (U, V)) -> (U, [V]) { var mapped = [V]() var acc = initial @@ -1027,9 +1044,9 @@ internal extension Array { /** self.reduce with initial value self.first() */ - func reduce (combine: (Element, Element) -> Element) -> Element? { + public func reduce (_ combine: (Element, Element) -> Element) -> Element? { if let firstElement = first { - return skip(1).reduce(firstElement, combine: combine) + return skip(1).reduce(firstElement, combine) } return nil @@ -1038,34 +1055,34 @@ 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 { - return reverse().reduce(initial, combine: combine) + @available(*, unavailable, message: "use 'reverse().reduce' instead") public func reduceRight (_ initial: U, combine: (U, Element) -> U) -> U { + return reversed().reduce(initial, combine) } /** self.reduceRight with initial value self.last() */ - @availability(*, unavailable, message="use 'reverse().reduce' instead") func reduceRight (combine: (Element, Element) -> Element) -> Element? { - return reverse().reduce(combine) + @available(*, unavailable, message: "use 'reverse().reduce' instead") public func reduceRight (_ combine: (Element, Element) -> Element) -> Element? { + return reversed().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 { + public func at (_ indexes: Int...) -> Array { return indexes.map { self.get($0)! } } /** 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] { + public func toDictionary (_ keySelector:(Element) -> U) -> [U: Element] { var result: [U: Element] = [:] for item in self { result[keySelector(item)] = item @@ -1077,10 +1094,10 @@ 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] { + public func toDictionary (_ transform: (Element) -> (key: K, value: V)?) -> [K: V] { var result: [K: V] = [:] for item in self { if let entry = transform(item) { @@ -1094,26 +1111,29 @@ internal extension Array { /** Flattens a nested Array self to an array of OutType objects. - :returns: Flattened array + - returns: Flattened array */ - func flatten () -> [OutType] { + public func flatten () -> [OutType] { var result = [OutType]() - let reflection = reflect(self) - - for i in 0.. [AnyObject] { - var result = [AnyObject]() + public func flattenAny () -> [Any] { + var result = [Any]() for item in self { if let array = item as? NSArray { @@ -1129,20 +1149,20 @@ 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") public func sortBy (_ isOrderedBefore: (Element, Element) -> Bool) -> [Element] { + return sorted(by: 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) -> ()) { + public func cycle (_ n: Int? = nil, block: (Element) -> ()) { var cyclesRun = 0 while true { if let n = n { @@ -1153,7 +1173,7 @@ internal extension Array { for item in self { block(item) } - cyclesRun++ + cyclesRun += 1 } } @@ -1164,10 +1184,10 @@ 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? { + public func bSearch (_ block: (Element) -> (Bool)) -> Element? { if count == 0 { return nil } @@ -1175,7 +1195,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,10 +1218,10 @@ 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? { + /*public func bSearch (block: (Element) -> (Int)) -> Element? { let match = bSearch { item in block(item) >= 0 } @@ -1210,24 +1230,24 @@ internal extension Array { } else { return nil } - } + }*/ /** 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) }) + public func sortUsing (_ block: ((Element) -> U)) -> [Element] { + return self.sorted(by: { 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? { + public mutating func pop () -> Element? { if self.isEmpty { return nil @@ -1240,55 +1260,55 @@ internal extension Array { /** Same as append. - :param: newElement Element to append + - parameter newElement: Element to append */ - mutating func push (newElement: Element) { + public mutating func push (_ newElement: Element) { return append(newElement) } /** Returns the first element of self and removes it from the array. - :returns: The removed element + - returns: The removed element */ - mutating func shift () -> Element? { + public mutating func shift () -> Element? { if self.isEmpty { return nil } - return removeAtIndex(0) + return self.remove(at: 0) } /** 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) + public mutating func unshift (_ newElement: Element) { + insert(newElement, at: 0) } /** 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) { + public mutating func insert (_ newArray: Array, atIndex: Int) { self = take(atIndex) + newArray + skip(atIndex) } /** 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) { + public mutating func remove (_ element: U) { let anotherSelf = self - removeAll(keepCapacity: true) + removeAll(keepingCapacity: true) anotherSelf.each { (index: Int, current: Element) in @@ -1301,99 +1321,79 @@ 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") public func range (_ range: CountableRange) -> [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) + let start = Swift.max(0, rangeAsArray.lowerBound) + let end = Swift.min(rangeAsArray.upperBound, count) if start > end { return [] } - return Array(self[Range(start: start, end: end)] as ArraySlice) - } - - /** - 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 - */ - subscript (interval: HalfOpenInterval) -> Array { - return self[rangeAsArray: Range(start: interval.start, end: interval.end)] - } - - /** - 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 - */ - subscript (interval: ClosedInterval) -> Array { - return self[rangeAsArray: Range(start: interval.start, end: interval.end + 1)] + return Array(self[start ..< end] as ArraySlice) } /** 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 return indexes.map { self[$0] } } - } + /** Remove an element from the array */ -public func - (first: [T], second: T) -> [T] { +public func - (first: [Element], second: Element) -> [Element] { return first - [second] } /** Difference operator */ -public func - (first: [T], second: [T]) -> [T] { +public func - (first: [Element], second: [Element]) -> [Element] { return first.difference(second) } /** Intersection operator */ -public func & (first: [T], second: [T]) -> [T] { +public func & (first: [Element], second: [Element]) -> [Element] { return first.intersection(second) } /** Union operator */ -public func | (first: [T], second: [T]) -> [T] { +public func | (first: [Element], second: [Element]) -> [Element] { return first.union(second) } /** 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 +1406,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..3e5ec0d 100644 --- a/ExSwift/Dictionary.swift +++ b/ExSwift/Dictionary.swift @@ -15,10 +15,10 @@ 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] { + func difference (_ dictionaries: [Key: V]...) -> [Key: V] { var result = [Key: V]() @@ -32,7 +32,7 @@ internal extension Dictionary { for dictionary in dictionaries { for (key, value) in dictionary { if result.has(key) && result[key] == value { - result.removeValueForKey(key) + result.removeValue(forKey: key) } } } @@ -44,10 +44,10 @@ 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 { + func union (_ dictionaries: Dictionary...) -> Dictionary { var result = self @@ -65,10 +65,10 @@ 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] { + func intersection (_ dictionaries: [K: V]...) -> [K: V] where K: Equatable, V: Equatable { // Casts self from [Key: Value] to [K: V] let filtered = mapFilter { (item, value) -> (K, V)? in @@ -90,21 +90,21 @@ 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 + func has (_ key: Key) -> Bool { + return index(forKey: key) != nil } /** 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] { + func toArray (_ map: (Key, Value) -> V) -> [V] { var mapped = [V]() @@ -120,10 +120,10 @@ 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] { + func mapValues (_ map: (Key, Value) -> V) -> [Key: V] { var mapped = [Key: V]() @@ -139,10 +139,10 @@ 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] { + func mapFilterValues (_ map: (Key, Value) -> V?) -> [Key: V] { var mapped = [Key: V]() @@ -160,10 +160,10 @@ 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] { + func mapFilter (_ map: (Key, Value) -> (K, V)?) -> [K: V] { var mapped = [K: V]() @@ -181,10 +181,10 @@ 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] { + func map (_ map: (Key, Value) -> (K, V)) -> [K: V] { var mapped = [K: V]() @@ -200,9 +200,9 @@ 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) -> ()) { + func each (_ each: (Key, Value) -> ()) { for (key, value) in self { each(key, value) @@ -214,10 +214,10 @@ 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 { + func filter (_ test: (Key, Value) -> Bool) -> Dictionary { var result = Dictionary() @@ -236,10 +236,10 @@ 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]] { + func groupBy (_ group: (Key, Value) -> T) -> [T: [Value]] { var result = [T: [Value]]() @@ -262,10 +262,10 @@ 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] { + func countBy (_ group: (Key, Value) -> (T)) -> [T: Int] { var result = [T: Int]() @@ -275,7 +275,7 @@ internal extension Dictionary { // If element has already been added to dictionary, append to it. If not, create one. if result.has(groupKey) { - result[groupKey]!++ + result[groupKey]! += 1 } else { result[groupKey] = 1 } @@ -287,10 +287,10 @@ 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 { + func all (_ test: (Key, Value) -> (Bool)) -> Bool { for (key, value) in self { if !test(key, value) { @@ -305,10 +305,10 @@ 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 { + func any (_ test: (Key, Value) -> (Bool)) -> Bool { for (key, value) in self { if test(key, value) { @@ -324,41 +324,29 @@ 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 { + func countWhere (_ test: (Key, Value) -> (Bool)) -> Int { var result = 0 for (key, value) in self { if test(key, value) { - result++ + result += 1 } } 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 { + func pick (_ keys: [Key]) -> Dictionary { return filter { (key: Key, _) -> Bool in return keys.contains(key) } @@ -367,20 +355,20 @@ 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)) + func pick (_ keys: Key...) -> Dictionary { + return pick(unsafeBitCast(keys, to: [Key].self)) } /** 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 { + func at (_ keys: Key...) -> Dictionary { return pick(keys) } @@ -388,11 +376,11 @@ 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 { - return (key, removeValueForKey(key)!) + return (key, removeValue(forKey: key)!) } return nil diff --git a/ExSwift/Double.swift b/ExSwift/Double.swift index 9acfaf6..4fb4ec5 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,11 +58,11 @@ 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 { + func clamp (_ min: Double, _ max: Double) -> Double { return Swift.max(min, Swift.min(max, self)) } @@ -72,8 +72,8 @@ public extension Double { :params: increment the increment to round to */ - func roundToNearest(increment: Double) -> Double { - let remainder = self % increment + func roundToNearest(_ increment: Double) -> Double { + let remainder = self.truncatingRemainder(dividingBy: increment) return remainder < increment / 2 ? self - remainder : self - remainder + increment } @@ -82,9 +82,9 @@ public extension Double { :params: min :params: max - :returns: Random number + - returns: Random number */ - static func random(min: Double = 0, max: Double) -> Double { + static func random(_ min: Double = 0, max: Double) -> Double { let diff = max - min; let rand = Double(arc4random() % (UInt32(RAND_MAX) + 1)) return ((rand / Double(RAND_MAX)) * diff) + min; diff --git a/ExSwift/ExSwift.swift b/ExSwift/ExSwift.swift index 82c5dc0..cab7c00 100644 --- a/ExSwift/ExSwift.swift +++ b/ExSwift/ExSwift.swift @@ -8,25 +8,25 @@ import Foundation -infix operator =~ {} -infix operator |~ {} -infix operator .. {} -infix operator <=> {} +infix operator =~ +infix operator |~ +infix operator .. +infix operator <=> public typealias Ex = ExSwift -public class ExSwift { +open class ExSwift { /** Creates a wrapper that, executes function only after being called n times. - :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?) { + open class func after (_ n: Int, function: @escaping (P...) -> T) -> ((P...) -> T?) { - typealias Function = [P] -> T + typealias Function = ([P]) -> T var times = n @@ -34,9 +34,9 @@ public class ExSwift { (params: P...) -> T? in // Workaround for the now illegal (T...) type. - let adaptedFunction = unsafeBitCast(function, Function.self) - - if times-- <= 0 { + let adaptedFunction = unsafeBitCast(function, to: Function.self) + times -= 1 + if times <= 0 { return adaptedFunction(params) } @@ -48,11 +48,11 @@ 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?) { + /*public class func after (n: Int, function: Void -> T) -> (Void -> T?) { func callAfter (args: Any?...) -> T { return function() } @@ -60,18 +60,18 @@ public class ExSwift { let f = ExSwift.after(n, function: callAfter) return { f([nil]) } - } + }*/ /** 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) { + open class func once (_ function: @escaping (P...) -> T) -> ((P...) -> T) { - typealias Function = [P] -> T + typealias Function = ([P]) -> T var returnValue: T? = nil @@ -81,7 +81,7 @@ public class ExSwift { return returnValue! } - let adaptedFunction = unsafeBitCast(function, Function.self) + let adaptedFunction = unsafeBitCast(function, to: Function.self) returnValue = adaptedFunction(params) return returnValue! @@ -94,31 +94,31 @@ 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) { + /*public class func once (function: Void -> T) -> (Void -> T) { let f = ExSwift.once { (params: Any?...) -> T in return function() } return { f([nil]) } - } + }*/ /** Creates a wrapper that, when called, invokes function with any additional 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 + open class func partial (_ function: @escaping (P...) -> T, _ parameters: P...) -> ((P...) -> T) { + typealias Function = ([P]) -> T return { (params: P...) -> T in - let adaptedFunction = unsafeBitCast(function, Function.self) + let adaptedFunction = unsafeBitCast(function, to: Function.self) return adaptedFunction(parameters + params) } } @@ -127,15 +127,15 @@ 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 + open class func bind (_ function: @escaping (P...) -> T, _ parameters: P...) -> ((Void) -> T) { + typealias Function = ([P]) -> T return { Void -> T in - let adaptedFunction = unsafeBitCast(function, Function.self) + let adaptedFunction = unsafeBitCast(function, to: Function.self) return adaptedFunction(parameters) } } @@ -143,10 +143,10 @@ 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) { + open class func cached (_ function: @escaping (P) -> R) -> ((P) -> R) { var cache = [P:R]() return { (param: P) -> R in @@ -165,19 +165,19 @@ 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 - typealias Hash = [P] -> P + open class func cached (_ function: @escaping (P...) -> R, hash: @escaping ((P...) -> P)) -> ((P...) -> R) { + typealias Function = ([P]) -> R + typealias Hash = ([P]) -> P var cache = [P:R]() return { (params: P...) -> R in - let adaptedFunction = unsafeBitCast(function, Function.self) - let adaptedHash = unsafeBitCast(hash, Hash.self) + let adaptedFunction = unsafeBitCast(function, to: Function.self) + let adaptedHash = unsafeBitCast(hash, to: Hash.self) let key = adaptedHash(params) @@ -194,35 +194,32 @@ 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) { + open class func cached (_ function: @escaping (P...) -> R) -> ((P...) -> R) { return cached(function, hash: { (params: P...) -> P in return params[0] }) } /** 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 + var options = NSRegularExpression.Options.dotMatchesLineSeparators.rawValue if ignoreCase { - options = NSRegularExpressionOptions.CaseInsensitive.rawValue | options + options = NSRegularExpression.Options.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: NSRegularExpression.Options(rawValue: options)) } - + } func <=> (lhs: T, rhs: T) -> Int { @@ -246,32 +243,30 @@ 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) + let mirrorChildrenCollection = AnyRandomAccessCollection(reflection.children) // object has an Objective-C type if let obj = object as? T { // object has type T result.append(obj) - } else if reflection.disposition == .ObjCObject { + } else if reflection.subjectType == NSArray.self { - 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 { + } else if let bridged = mirrorChildrenCollection as? T { result.append(bridged) } - } else if reflection.disposition == .IndexContainer { + + } else if object is Array { // object is a native Swift array // recursively convert each item - (0.. 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,22 +58,22 @@ 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 { + func clamp (_ min: Float, _ max: Float) -> Float { return Swift.max(min, Swift.min(max, self)) } /** 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 { + static func random(_ min: Float = 0, max: Float) -> Float { let diff = max - min; let rand = Float(arc4random() % (UInt32(RAND_MAX) + 1)) return ((rand / Float(RAND_MAX)) * diff) + min; diff --git a/ExSwift/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..c658c87 100644 --- a/ExSwift/Int.swift +++ b/ExSwift/Int.swift @@ -13,34 +13,34 @@ public extension Int { /** Calls function self times. - :param: function Function to call + - parameter function: Function to call */ - func times (function: Void -> T) { - (0.. (_ function: @escaping (Void) -> T) { + (0.. Void) { - (0.. Void) { + (0.. (function: (Int) -> T) { - (0.. (_ function: @escaping (Int) -> T) { + (0.. 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,10 +58,10 @@ 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) -> ()) { + func upTo (_ limit: Int, function: (Int) -> ()) { if limit < self { return } @@ -72,70 +72,70 @@ 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) -> ()) { + func downTo (_ limit: Int, function: (Int) -> ()) { if limit > self { return } - Array(limit...self).reverse().each(function) + Array(Array(limit...self).reversed()).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) + func clamp (_ range: Range) -> Int { + return clamp(range.lowerBound, range.upperBound - 1) } /** 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 { + func clamp (_ min: Int, _ max: Int) -> Int { return Swift.max(min, Swift.min(max, self)) } /** 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 { + func isIn (_ range: Range, strict: Bool = false) -> Bool { if strict { - return range.startIndex < self && self < range.endIndex - 1 + return range.lowerBound < self && self < range.upperBound - 1 } - return range.startIndex <= self && self <= range.endIndex - 1 + return range.lowerBound <= self && self <= range.upperBound - 1 } /** 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 { + func isIn (_ interval: ClosedRange) -> Bool { return interval.contains(self) } /** 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 { + func isIn (_ interval: Range) -> 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,27 +169,27 @@ public extension Int { /** Greatest common divisor of self and n. - :param: n - :returns: GCD + - parameter n: + - returns: GCD */ - func gcd (n: Int) -> Int { + func gcd (_ n: Int) -> Int { return n == 0 ? self : n.gcd(self % n) } /** Least common multiple of self and n - :param: n - :returns: LCM + - parameter n: + - returns: LCM */ - func lcm (n: Int) -> Int { + func lcm (_ n: Int) -> Int { return (self * n).abs() / gcd(n) } /** Computes the factorial of self - :returns: Factorial + - returns: Factorial */ func factorial () -> Int { return self == 0 ? 1 : self * (self - 1).factorial() @@ -198,11 +198,11 @@ 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 { + static func random(_ min: Int = 0, max: Int) -> Int { return Int(arc4random_uniform(UInt32((max - min) + 1))) + min } @@ -213,43 +213,43 @@ public extension Int { */ public extension Int { - var years: NSTimeInterval { + var years: TimeInterval { return 365 * self.days } - var year: NSTimeInterval { + var year: TimeInterval { return self.years } - var days: NSTimeInterval { + var days: TimeInterval { return 24 * self.hours } - var day: NSTimeInterval { + var day: TimeInterval { return self.days } - var hours: NSTimeInterval { + var hours: TimeInterval { return 60 * self.minutes } - var hour: NSTimeInterval { + var hour: TimeInterval { return self.hours } - var minutes: NSTimeInterval { + var minutes: TimeInterval { return 60 * self.seconds } - var minute: NSTimeInterval { + var minute: TimeInterval { return self.minutes } - var seconds: NSTimeInterval { - return NSTimeInterval(self) + var seconds: TimeInterval { + return TimeInterval(self) } - var second: NSTimeInterval { + var second: TimeInterval { return self.seconds } diff --git a/ExSwift/NSArray.swift b/ExSwift/NSArray.swift index d2c3a9e..7fdede7 100644 --- a/ExSwift/NSArray.swift +++ b/ExSwift/NSArray.swift @@ -10,55 +10,56 @@ import Foundation public extension NSArray { - /** - Converts an NSArray object to an OutType[] array containing the items in the NSArray of type OutType. - - :returns: Array of Swift objects - */ - func cast () -> [OutType] { - var result = [OutType]() - - for item : AnyObject in self { - result += Ex.bridgeObjCObject(item) as [OutType] - } - - return result + /** + Converts an NSArray object to an OutType[] array containing the items in the NSArray of type OutType. + + - returns: Array of Swift objects + */ + public func cast () -> [OutType] { + var result = [OutType]() + + for item : Any in self { + result += Ex.bridgeObjCObject(item) as [OutType] } - /** - Flattens a multidimensional NSArray to an OutType[] array - containing the items in the NSArray that can be bridged from their ObjC type to OutType. - - :returns: Flattened array - */ - func flatten () -> [OutType] { - var result = [OutType]() - let reflection = reflect(self) - - for i in 0.. () -> [OutType] { + var result = [OutType]() + let mirror = Mirror(reflecting: self) + if let mirrorChildrenCollection = AnyRandomAccessCollection(mirror.children) { + for (_, value) in mirrorChildrenCollection { + result += Ex.bridgeObjCObject(value) as [OutType] + } } - - /** - Flattens a multidimensional NSArray to a [AnyObject]. - - :returns: Flattened array - */ - func flattenAny () -> [AnyObject] { - var result = [AnyObject]() - - for item in self { - if let array = item as? NSArray { - result += array.flattenAny() - } else { - result.append(item) - } - } - - return result + + return result + } + + /** + Flattens a multidimensional NSArray to a [Any]. + + - returns: Flattened array + */ + public func flattenAny () -> [Any] { + var result = [Any]() + + for item in self { + if let array = item as? NSArray { + result += array.flattenAny() + } else { + result.append(item) + } } - + + return result + } + } diff --git a/ExSwift/NSDate.swift b/ExSwift/NSDate.swift index 50d758e..b598acd 100644 --- a/ExSwift/NSDate.swift +++ b/ExSwift/NSDate.swift @@ -8,311 +8,278 @@ import Foundation -public extension NSDate { - - // MARK: NSDate Manipulation - - /** - 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 - */ - 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() - - let version = floor(NSFoundationVersionNumber) - - if version <= NSFoundationVersionNumber10_9_2 { - var component = NSDateComponents() - component.setValue(seconds, forComponent: .CalendarUnitSecond) - - var date : NSDate! = calendar.dateByAddingComponents(component, toDate: self, options: nil)! - component = NSDateComponents() - component.setValue(minutes, forComponent: .CalendarUnitMinute) - date = calendar.dateByAddingComponents(component, toDate: date, options: nil)! - - component = NSDateComponents() - component.setValue(hours, forComponent: .CalendarUnitHour) - date = calendar.dateByAddingComponents(component, toDate: date, options: nil)! - - component = NSDateComponents() - component.setValue(days, forComponent: .CalendarUnitDay) - date = calendar.dateByAddingComponents(component, toDate: date, options: nil)! - - component = NSDateComponents() - component.setValue(weeks, forComponent: .CalendarUnitWeekOfMonth) - date = calendar.dateByAddingComponents(component, toDate: date, options: nil)! - - component = NSDateComponents() - component.setValue(months, forComponent: .CalendarUnitMonth) - date = calendar.dateByAddingComponents(component, toDate: date, options: nil)! - - component = NSDateComponents() - component.setValue(years, forComponent: .CalendarUnitYear) - date = calendar.dateByAddingComponents(component, toDate: date, options: nil)! - 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) - 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 - */ - public func addSeconds (seconds: Int) -> NSDate { - return add(seconds: seconds) - } - - /** - 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 - */ - public func addMinutes (minutes: Int) -> NSDate { - return add(minutes: minutes) - } - - /** - 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 - */ - public func addHours(hours: Int) -> NSDate { - return add(hours: hours) - } - - /** - 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 - */ - public func addDays(days: Int) -> NSDate { - return add(days: days) - } - - /** - 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 - */ - public func addWeeks(weeks: Int) -> NSDate { - return add(weeks: weeks) - } - - - /** - 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 - */ - - public func addMonths(months: Int) -> NSDate { - return add(months: months) - } - - /** - 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 - */ - public func addYears(years: Int) -> NSDate { - return add(years: years) - } - - // MARK: Date comparison - - /** - Checks if self is after input NSDate - - :param: 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) - } - - /** - Checks if self is before input NSDate - - :param: 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) - } - - - // MARK: Getter - - /** - Date year - */ - public var year : Int { - get { - return getComponent(.CalendarUnitYear) - } - } +public extension Date { - /** - Date month - */ - public var month : Int { - get { - return getComponent(.CalendarUnitMonth) - } - } - - /** - Date weekday - */ - public var weekday : Int { - get { - return getComponent(.CalendarUnitWeekday) - } - } + // MARK: NSDate Manipulation - /** - Date weekMonth - */ - public var weekMonth : Int { - get { - return getComponent(.CalendarUnitWeekOfMonth) - } - } + /** + Returns a new NSDate object representing the date calculated by adding the amount specified to self date - - /** - Date days - */ - public var days : Int { - get { - return getComponent(.CalendarUnitDay) - } - } - - /** - Date hours - */ - public var hours : Int { - - get { - return getComponent(.CalendarUnitHour) - } + - parameter seconds: number of seconds to add + - parameter minutes: number of minutes to add + - parameter hours: number of hours to add + - parameter days: number of days to add + - parameter weeks: number of weeks to add + - parameter months: number of months to add + - parameter years: number of years to add + - returns: the NSDate computed + */ + public func add(seconds: Int = 0, minutes: Int = 0, hours: Int = 0, days: Int = 0, weeks: Int = 0, months: Int = 0, years: Int = 0) -> Date { + let calendar = Calendar.current + let version = floor(NSFoundationVersionNumber) + + if version <= NSFoundationVersionNumber10_9_2 { + var component = DateComponents() + component.setValue(seconds, for: .second) + + var date : Date! = calendar.date(byAdding: component, to: self, wrappingComponents: false)! + component = DateComponents() + component.setValue(minutes, for: .minute) + date = calendar.date(byAdding: component, to: date, wrappingComponents: false)! + + component = DateComponents() + component.setValue(hours, for: .hour) + date = calendar.date(byAdding: component, to: date, wrappingComponents: false)! + + component = DateComponents() + component.setValue(days, for: .day) + date = calendar.date(byAdding: component, to: date, wrappingComponents: false)! + + component = DateComponents() + component.setValue(weeks, for: .weekOfMonth) + date = calendar.date(byAdding: component, to: date, wrappingComponents: false)! + + component = DateComponents() + component.setValue(months, for: .month) + date = calendar.date(byAdding: component, to: date, wrappingComponents: false)! + + component = DateComponents() + component.setValue(years, for: .year) + date = calendar.date(byAdding: component, to: date, wrappingComponents: false)! + return date } - - /** - Date minuts - */ - public var minutes : Int { - get { - return getComponent(.CalendarUnitMinute) - } + + var date : Date! = calendar.date(byAdding: Calendar.Component.second, value: seconds, to: self, wrappingComponents: false) + date = calendar.date(byAdding: Calendar.Component.minute, value: minutes, to: date, wrappingComponents: false) + date = calendar.date(byAdding: Calendar.Component.day, value: days, to: date, wrappingComponents: false) + date = calendar.date(byAdding: Calendar.Component.hour, value: hours, to: date, wrappingComponents: false) + date = calendar.date(byAdding: Calendar.Component.weekOfMonth, value: weeks, to: date, wrappingComponents: false) + date = calendar.date(byAdding: Calendar.Component.month, value: months, to: date, wrappingComponents: false) + date = calendar.date(byAdding: Calendar.Component.year, value: years, to: date, wrappingComponents: false) + return date + } + + /** + Returns a new NSDate object representing the date calculated by adding an amount of seconds to self date + + - parameter seconds: number of seconds to add + - returns: the NSDate computed + */ + public func addSeconds (_ seconds: Int) -> Date { + return add(seconds: seconds) + } + + /** + Returns a new NSDate object representing the date calculated by adding an amount of minutes to self date + + - parameter minutes: number of minutes to add + - returns: the NSDate computed + */ + public func addMinutes (_ minutes: Int) -> Date { + return add(minutes: minutes) + } + + /** + Returns a new NSDate object representing the date calculated by adding an amount of hours to self date + + - parameter hours: number of hours to add + - returns: the NSDate computed + */ + public func addHours(_ hours: Int) -> Date { + return add(hours: hours) + } + + /** + Returns a new NSDate object representing the date calculated by adding an amount of days to self date + + - parameter days: number of days to add + - returns: the NSDate computed + */ + public func addDays(_ days: Int) -> Date { + return add(days: days) + } + + /** + Returns a new NSDate object representing the date calculated by adding an amount of weeks to self date + + - parameter weeks: number of weeks to add + - returns: the NSDate computed + */ + public func addWeeks(_ weeks: Int) -> Date { + return add(weeks: weeks) + } + + + /** + Returns a new NSDate object representing the date calculated by adding an amount of months to self date + + - parameter months: number of months to add + - returns: the NSDate computed + */ + + public func addMonths(_ months: Int) -> Date { + return add(months: months) + } + + /** + Returns a new NSDate object representing the date calculated by adding an amount of years to self date + + - parameter years: number of year to add + - returns: the NSDate computed + */ + public func addYears(_ years: Int) -> Date { + return add(years: years) + } + + // MARK: Date comparison + + /** + Checks if self is after input NSDate + + - parameter date: NSDate to compare + - returns: True if self is after the input NSDate, false otherwise + */ + public func isAfter(_ date: Date) -> Bool{ + return (self.compare(date) == ComparisonResult.orderedDescending) + } + + /** + Checks if self is before input NSDate + + - parameter date: NSDate to compare + - returns: True if self is before the input NSDate, false otherwise + */ + public func isBefore(_ date: Date) -> Bool{ + return (self.compare(date) == ComparisonResult.orderedAscending) + } + + + // MARK: Getter + + /** + Date year + */ + public var year : Int { + get { + return getComponent(.year) } - - /** - Date seconds - */ - public var seconds : Int { - get { - return getComponent(.CalendarUnitSecond) - } + } + + /** + Date month + */ + public var month : Int { + get { + return getComponent(.month) } - - /** - Returns the value of the NSDate component - - :param: component NSCalendarUnit - :returns: the value of the component - */ - - public func getComponent (component : NSCalendarUnit) -> Int { - let calendar = NSCalendar.currentCalendar() - let components = calendar.components(component, fromDate: self) - - return components.valueForComponent(component) + } + + /** + Date weekday + */ + public var weekday : Int { + get { + return getComponent(.weekday) } -} + } -extension NSDate: Strideable { - public func distanceTo(other: NSDate) -> NSTimeInterval { - return other - self + /** + Date weekMonth + */ + public var weekMonth : Int { + get { + return getComponent(.weekOfMonth) } - - public func advancedBy(n: NSTimeInterval) -> Self { - return self.dynamicType(timeIntervalSinceReferenceDate: self.timeIntervalSinceReferenceDate + n) + } + + + /** + Date days + */ + public var days : Int { + get { + return getComponent(.day) } -} -// MARK: Arithmetic + } -func +(date: NSDate, timeInterval: Int) -> NSDate { - return date + NSTimeInterval(timeInterval) -} + /** + Date hours + */ + public var hours : Int { -func -(date: NSDate, timeInterval: Int) -> NSDate { - return date - NSTimeInterval(timeInterval) -} + get { + return getComponent(.hour) + } + } -func +=(inout date: NSDate, timeInterval: Int) { - date = date + timeInterval -} + /** + Date minuts + */ + public var minutes : Int { + get { + return getComponent(.minute) + } + } -func -=(inout date: NSDate, timeInterval: Int) { - date = date - timeInterval -} + /** + Date seconds + */ + public var seconds : Int { + get { + return getComponent(.second) + } + } -func +(date: NSDate, timeInterval: Double) -> NSDate { - return date.dateByAddingTimeInterval(NSTimeInterval(timeInterval)) -} + /** + Returns the value of the NSDate component -func -(date: NSDate, timeInterval: Double) -> NSDate { - return date.dateByAddingTimeInterval(NSTimeInterval(-timeInterval)) -} + - parameter component: NSCalendarUnit + - returns: the value of the component + */ -func +=(inout date: NSDate, timeInterval: Double) { - date = date + timeInterval + public func getComponent (_ component : Calendar.Component) -> Int { + let calendar = Calendar.current + return calendar.component(component, from: self) + } } -func -=(inout date: NSDate, timeInterval: Double) { - date = date - timeInterval +extension Date: Strideable { + public func distance(to other: Date) -> TimeInterval { + return other - self + } + + public func advanced(by n: TimeInterval) -> Date { + return type(of: self).init(timeIntervalSinceReferenceDate: self.timeIntervalSinceReferenceDate + n) + } } +// MARK: Arithmetic -func -(date: NSDate, otherDate: NSDate) -> NSTimeInterval { - return date.timeIntervalSinceDate(otherDate) +public func +(date: Date, timeInterval: Int) -> Date { + return date + Double(timeInterval) } -extension NSDate: Equatable { +public func -(date: Date, timeInterval: Int) -> Date { + return date - Double(timeInterval) } -public func ==(lhs: NSDate, rhs: NSDate) -> Bool { - return lhs.compare(rhs) == NSComparisonResult.OrderedSame +public func +=(date: inout Date, timeInterval: Int) { + date = date + timeInterval } -extension NSDate: Comparable { +public func -=(date: inout Date, timeInterval: Int) { + date = date - timeInterval } -public func <(lhs: NSDate, rhs: NSDate) -> Bool { - return lhs.compare(rhs) == NSComparisonResult.OrderedAscending +public func -(date: Date, otherDate: Date) -> TimeInterval { + return date.timeIntervalSince(otherDate) } diff --git a/ExSwift/Range.swift b/ExSwift/Range.swift index 051368d..b82afeb 100644 --- a/ExSwift/Range.swift +++ b/ExSwift/Range.swift @@ -8,73 +8,135 @@ import Foundation -internal extension Range { - - /** - For each element in the range invokes function. - - :param: function Function to call - */ - func times (function: () -> ()) { - each { (current: T) -> () in - function() - } +public extension CountableRange { + + /** + For each element in the range invokes function. + + - parameter function: Function to call + */ + public func times (_ function: () -> ()) { + each { (current: Bound) -> () in + function() } + } + + /** + For each element in the range invokes function passing the element as argument. - /** - For each element in the range invokes function passing the element as argument. - - :param: function Function to invoke - */ - func times (function: (T) -> ()) { - each (function) + - parameter function: Function to invoke + */ + public func times (_ function: (Bound) -> ()) { + each (function) + } + + /** + For each element in the range invokes function passing the element as argument. + + - parameter function: Function to invoke + */ + public func each (_ function: (Bound) -> ()) { + for i in self { + function(i) } + } + + /** + Returns each element of the range in an array + + - returns: Each element of the range in an array + */ + public func toArray () -> [Bound] { + var result: [Bound] = [] + for i in self { + result.append(i) + } + return result + } + + /** + Range of Int with random bounds between from and to (inclusive). + + - parameter from: Lower bound + - parameter to: Upper bound + - returns: Random range + */ + public static func random (_ from: Int, to: Int) -> CountableClosedRange { + let lowerBound = Int.random(from, max: to) + let upperBound = Int.random(lowerBound, max: to) + + return lowerBound...upperBound + } - /** - For each element in the range invokes function passing the element as argument. - - :param: function Function to invoke - */ - func each (function: (T) -> ()) { - for i in self { - function(i) - } +} + +public extension CountableClosedRange { + + /** + For each element in the range invokes function. + + - parameter function: Function to call + */ + public func times (_ function: () -> ()) { + each { (current: Bound) -> () in + function() } + } + + /** + For each element in the range invokes function passing the element as argument. + + - parameter function: Function to invoke + */ + public func times (_ function: (Bound) -> ()) { + each (function) + } - /** - Returns each element of the range in an array - - :returns: Each element of the range in an array - */ - func toArray () -> [T] { - var result: [T] = [] - for i in self { - result.append(i) - } - return result + /** + For each element in the range invokes function passing the element as argument. + + - parameter function: Function to invoke + */ + public func each (_ function: (Bound) -> ()) { + for i in self { + function(i) } + } + + /** + Returns each element of the range in an array - /** - Range of Int with random bounds between from and to (inclusive). - - :param: from Lower bound - :param: 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) - - return lowerBound...upperBound + - returns: Each element of the range in an array + */ + public func toArray () -> [Bound] { + var result: [Bound] = [] + for i in self { + result.append(i) } + return result + } + + /** + Range of Int with random bounds between from and to (inclusive). + + - parameter from: Lower bound + - parameter to: Upper bound + - returns: Random range + */ + public static func random (_ from: Int, to: Int) -> CountableClosedRange { + let lowerBound = Int.random(from, max: to) + let upperBound = Int.random(lowerBound, max: to) + + return lowerBound...upperBound + } } /** -* Operator == to compare 2 ranges first, second by start & end indexes. If first.startIndex is equal to -* second.startIndex and first.endIndex is equal to second.endIndex the ranges are considered equal. -*/ -public func == (first: Range, second: Range) -> Bool { - return first.startIndex == second.startIndex && - first.endIndex == second.endIndex + * Operator == to compare 2 ranges first, second by start & end indexes. If first.startIndex is equal to + * second.startIndex and first.endIndex is equal to second.endIndex the ranges are considered equal. + */ +public func == (first: Range, second: Range) -> Bool { + return first.lowerBound == second.lowerBound && + first.upperBound == second.upperBound } diff --git a/ExSwift/Sequence.swift b/ExSwift/Sequence.swift index 6aa19b3..60928a6 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() + var first: Element? { + let generator = self.makeIterator() 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() + func any (_ call: (Element) -> Bool) -> Bool { + let generator = self.makeIterator() while let nextItem = generator.next() { if call(nextItem) { return true @@ -39,13 +39,13 @@ 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() + func get (_ index: Int) -> Element? { + let generator = self.makeIterator() for _ in 0..<(index - 1) { - generator.next() + _ = generator.next() } return generator.next() } @@ -53,20 +53,20 @@ 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 { - return self.skip(range.startIndex).take(range.endIndex - range.startIndex) + func get (_ range: Range) -> AnySequence { + return self.skip(range.lowerBound).take(range.upperBound - range.lowerBound) } /** 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? { + func indexOf (_ item: U) -> Int? { var index = 0 for current in self { if let equatable = current as? U { @@ -74,7 +74,7 @@ internal extension SequenceOf { return index } } - index++ + index += 1 } return nil } @@ -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.makeIterator() for _ in 0.. Bool) -> SequenceOf { - return SequenceOf(lazy(self).filter(include)) + func filter(_ include: (Element) -> Bool) -> AnySequence { + return AnySequence(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: ((Element) -> Bool)) -> AnySequence { return self.filter { return !exclude($0) } @@ -118,36 +118,36 @@ 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:(Element) -> Bool) -> AnySequence { + let generator = self.makeIterator() + let checkingGenerator = self.makeIterator() var keepSkipping = true while keepSkipping { - var nextItem = checkingGenerator.next() + let nextItem = checkingGenerator.next() keepSkipping = nextItem != nil ? condition(nextItem!) : false if keepSkipping { - generator.next() + _ = 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() + func contains (_ item: Element) -> Bool { + let generator = self.makeIterator() while let nextItem = generator.next() { - if nextItem as! T == item { + if nextItem as! Element == item { return true } } @@ -157,30 +157,30 @@ 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:@escaping (Element?) -> 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] = [] + func toArray () -> [Element] { + var result: [Element] = [] for item in self { result.append(item) } @@ -191,20 +191,20 @@ internal extension SequenceOf { /** A sequence adapter that implements the 'take' functionality */ -public struct TakeSequence: SequenceType { - private let sequence: S - private let n: Int +public struct TakeSequence: Sequence { + fileprivate let sequence: S + fileprivate let n: Int public init(_ sequence: S, _ n: Int) { self.sequence = sequence self.n = n } - public func generate() -> GeneratorOf { + public func makeIterator() -> AnyIterator { var count = 0 - var generator = self.sequence.generate() - return GeneratorOf { - count++ + var generator = self.sequence.makeIterator() + return AnyIterator { + count += 1 if count > self.n { return nil } else { @@ -217,20 +217,20 @@ public struct TakeSequence: SequenceType { /** a sequence adapter that implements the 'takeWhile' functionality */ -public struct TakeWhileSequence: SequenceType { - private let sequence: S - private let condition: (S.Generator.Element?) -> Bool +public struct TakeWhileSequence: Sequence { + fileprivate let sequence: S + fileprivate let condition: (S.Iterator.Element?) -> Bool - public init(_ sequence:S, _ condition:(S.Generator.Element?) -> Bool) { + public init(_ sequence:S, _ condition:@escaping (S.Iterator.Element?) -> Bool) { self.sequence = sequence self.condition = condition } - public func generate() -> GeneratorOf { - var generator = self.sequence.generate() + public func makeIterator() -> AnyIterator { + var generator = self.sequence.makeIterator() var endConditionMet = false - return GeneratorOf { - let next: S.Generator.Element? = generator.next() + return AnyIterator { + let next: S.Iterator.Element? = generator.next() if !endConditionMet { endConditionMet = !self.condition(next) } diff --git a/ExSwift/String.swift b/ExSwift/String.swift index 95ff794..51bc9da 100644 --- a/ExSwift/String.swift +++ b/ExSwift/String.swift @@ -13,37 +13,43 @@ public extension String { /** String length */ - var length: Int { return count(self) } - - /** - self.capitalizedString shorthand - */ - var capitalized: String { return capitalizedString } + var length: Int { return self.characters.count } /** 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 { + if range.lowerBound < 0 || range.upperBound > self.length { return nil } - let range = Range(start: advance(startIndex, range.startIndex), end: advance(startIndex, range.endIndex)) + let range = characters.index(startIndex, offsetBy: range.lowerBound) ..< characters.index(startIndex, offsetBy: range.upperBound) return self[range] } + subscript (range: CountableRange) -> String? { + if range.lowerBound < 0 || range.upperBound > self.length { + return nil + } + + let range = characters.index(startIndex, offsetBy: range.lowerBound) ..< characters.index(startIndex, offsetBy: range.upperBound) + + return self[range] + } + + /** Equivalent to at. Takes a list of indexes and returns an Array containing the elements at the given indexes in self. - :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 +59,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,63 +73,62 @@ 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] { + func at (_ indexes: Int...) -> [String] { return indexes.map { self[$0]! } } /** 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] { + func at (_ indexes: [Int]) -> [String] { return indexes.map { self[$0]! } } /** 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 element == separator - }) + func explode (_ separator: Character) -> [String] { + return self.characters.split { $0 == 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.matches(in: 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.firstMatch(in: self, options: [], range: range) != nil } return nil @@ -132,15 +137,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.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: replacementString) } return nil @@ -149,11 +154,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,41 +172,41 @@ 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) { - return self[range.startIndex.. String { + if let range = rangeOfCharacter(from: set.inverted) { + return self[range.lowerBound.. String { + @available(*, unavailable, message: "use 'trimmedLeft' instead") func ltrimmed (_ set: CharacterSet = CharacterSet.whitespacesAndNewlines) -> String { return trimmedLeft(characterSet: set) } /** 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) { - return self[startIndex.. String { + if let range = rangeOfCharacter(from: set.inverted, options: NSString.CompareOptions.backwards) { + return self[startIndex.. String { + @available(*, unavailable, message: "use 'trimmedRight' instead") func rtrimmed (_ set: CharacterSet = CharacterSet.whitespacesAndNewlines) -> String { return trimmedRight(characterSet: set) } /** Strips whitespaces from both the beginning and the end of self. - :returns: Stripped string + - returns: Stripped string */ func trimmed () -> String { return trimmedLeft().trimmedRight() @@ -210,11 +215,12 @@ 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 { + static func random (_ length: Int = 0, charset: String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") -> String { + var len = length if len < 1 { len = Int.random(max: 16) @@ -224,7 +230,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,11 +241,11 @@ 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? { - let scanner = NSScanner(string: self) + let scanner = Scanner(string: self) var double: Double = 0 if scanner.scanDouble(&double) { @@ -253,11 +259,11 @@ 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? { - let scanner = NSScanner(string: self) + let scanner = Scanner(string: self) var float: Float = 0 if scanner.scanFloat(&float) { @@ -271,10 +277,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,10 +294,10 @@ 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 + let text = self.trimmed().lowercased() if text == "true" || text == "false" || text == "yes" || text == "no" { return (text as NSString).boolValue } @@ -303,26 +309,26 @@ 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() - dateFmt.timeZone = NSTimeZone.defaultTimeZone() + func toDate(_ format : String? = "yyyy-MM-dd") -> Date? { + let text = self.trimmed().lowercased() + let dateFmt = DateFormatter() + dateFmt.timeZone = TimeZone.current if let fmt = format { dateFmt.dateFormat = fmt } - return dateFmt.dateFromString(text) + return dateFmt.date(from: text) } /** 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) + func toDateTime(_ format : String? = "yyyy-MM-dd hh-mm-ss") -> Date? { + return toDate(format) } } @@ -343,10 +349,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.numberOfMatches(in: string, options: [], range: NSMakeRange(0, string.length)) return matches > 0 @@ -355,16 +361,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.numberOfMatches(in: 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)?.numberOfMatches(in: string, options: [], range: NSMakeRange(0, string.length)) { return matches > 0 } @@ -373,31 +379,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: Error? + 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: Error? + + 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