Created
January 31, 2015 15:49
-
-
Save ccwasden/c14d26f4e51fc1640d3a to your computer and use it in GitHub Desktop.
Some generic array utilities I use
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
func unwrapAndCollapse<T>(array:[T?]) -> [T] { | |
return array.reduce([]) { $1 != nil ? $0 + [$1!] : $0 } | |
} | |
func appendReplacingMatches<T>(first:[T], second:[T], matcher:((T,T)->Bool)) -> [T] { | |
var i = 0 | |
var finalArray = first | |
var appendArray = second | |
while i < first.count && appendArray.count > 0 { | |
let item = appendArray.first! | |
if matcher(item,first[i]) { | |
finalArray[i] = appendArray.removeAtIndex(0) | |
} | |
i++ | |
} | |
return finalArray + appendArray | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
unwrapAndCollapse
is useful for taking an array mapped to optional values and pulling out only the non-optionals. (for example the result ofUIImage(named:)
isOptional<UIImage>
, so mapping an array of image nameString
objects toUIImage
objects can be made easier by composingunwrapAndCollapse
). ie.I've found
appendReplacingMatches
most useful for writing paging UITableViews, etc. where the the next page of data coming down may have been shifted a row because of a new entry, and I want to avoid showing the same data in two sequential rows, so I will append the new rows, but replace any existing rows. ie.