Skip to content

Instantly share code, notes, and snippets.

@jbennett
Last active August 29, 2015 14:25
Show Gist options
  • Save jbennett/1d5057505420a22288bc to your computer and use it in GitHub Desktop.
Save jbennett/1d5057505420a22288bc to your computer and use it in GitHub Desktop.
/*:
# Swift Protocol Generics
In reference to [Secret Projects Diary #2: Swift 2.0 Protocols](http://inessential.com/2015/07/19/secret_projects_diary_2_swift_2_0_prot):
An variable of type `[Feed]` means that it could have a `LocalFeed` and a `FeedlyFeed`, which may be intentional, but i think not in this case. I am assuming that the `FeedlyFolder` could be typed as `[FeedlyFeed]`. If that is the case, making the Folder protocol be generic with a constraint of Feed should do the trick.
*/
import Cocoa
protocol Feed: Equatable {
var url: String {get}
}
func ==<T: Feed>(lhs: T, rhs: T) -> Bool {
return lhs.url == rhs.url
}
protocol Folder {
typealias FeedType: Feed
var feeds: [FeedType] {get}
func addFeeds(feedsToAdd: [FeedType])
}
class LocalFeed: Feed {
var url: String
init(url: String) {
self.url = url
}
}
class LocalFolder: Folder {
var feeds = [LocalFeed]()
func addFeeds(feedsToAdd: [LocalFeed]) {
for oneFeed in feedsToAdd {
if !feeds.contains(oneFeed) {
feeds += [oneFeed]
}
}
}
}
let folder = LocalFolder()
folder.addFeeds([LocalFeed(url: "Asdf"), LocalFeed(url: "123")])
folder.addFeeds([LocalFeed(url: "123"), LocalFeed(url: "xyz")])
folder.feeds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment