Last active
June 29, 2016 07:51
-
-
Save Alex-Ozun/a1c5d5ebda9bcb169b531a33d12de900 to your computer and use it in GitHub Desktop.
failingMap extension for SequanceType in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension SequenceType { | |
/** | |
Return an Optional<Array> containing the non-nil results of mapping transform over self or nil if any transform fails. | |
Complexity: O(N). | |
*/ | |
public func failingMap<T>(@noescape transform: (Self.Generator.Element) throws -> T?) rethrows -> [T]? { | |
let initialCapacity = self.underestimateCount() | |
var result = ContiguousArray<T>() | |
result.reserveCapacity(initialCapacity) | |
var generator = self.generate() | |
// Add elements up to the initial capacity without checking for regrowth. | |
for _ in 0..<initialCapacity { | |
guard let transformedElement = try transform(generator.next()!) else { return nil } | |
result.append(transformedElement) | |
} | |
// Add remaining elements, if any. | |
while let element = generator.next() { | |
guard let transformedElement = try transform(element) else { return nil } | |
result.append(transformedElement) | |
} | |
return Array(result) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Tests | |
let originalInvalid = ["1", "two", "3"] | |
var mapped = originalInvalid.map{str in Int(str)} | |
print(mapped) //"[Optional(1), nil, Optional(3)]" | |
var failingMapped = originalInvalid.failingMap{str in Int(str)} | |
print(failingMapped) //nil | |
let originalValid = ["1", "2", "3"] | |
mapped = originalValid.map{str in Int(str)} | |
print(mapped) //"[Optional(1), Optional(2), Optional(3)]" | |
failingMapped = originalValid.failingMap{str in Int(str)} | |
print(failingMapped) //"Optional([1, 2, 3])" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment