Skip to content

Instantly share code, notes, and snippets.

@ccwasden
Created January 31, 2015 15:49
Show Gist options
  • Save ccwasden/c14d26f4e51fc1640d3a to your computer and use it in GitHub Desktop.
Save ccwasden/c14d26f4e51fc1640d3a to your computer and use it in GitHub Desktop.
Some generic array utilities I use
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
}
@ccwasden
Copy link
Author

unwrapAndCollapse is useful for taking an array mapped to optional values and pulling out only the non-optionals. (for example the result of UIImage(named:) is Optional<UIImage>, so mapping an array of image name String objects to UIImage objects can be made easier by composing unwrapAndCollapse). ie.

// existing images in project named ["image-01","image-02", ... "image-60"]
let images:[UIImage] = unwrapAndCollapse(Array(1...60).map {
    UIImage(named: NSString(format: "image-%02d", Int($0)))
})

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.

self.tweetsViewController.tweets = appendReplacingMatches(self.tweetsViewController.tweets, newTweets) {
    $0.tweetId == $1.tweetId
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment