Skip to content

Instantly share code, notes, and snippets.

@cfilipov
Created December 11, 2015 21:10
Show Gist options
  • Save cfilipov/cd9ce0e5d6656a471e0f to your computer and use it in GitHub Desktop.
Save cfilipov/cd9ce0e5d6656a471e0f to your computer and use it in GitHub Desktop.
Swift 2.0 Protocols & Generic Constraints in response to http://inessential.com/2015/07/19/secret_projects_diary_2_swift_2_0_prot
// In the previous version https://gist.github.com/cfilipov/c9929dcb2cffcbf52a22, LocalFeed could only contain one type of Feed, this one allows it to store any feed type.
import Cocoa
protocol Feed: Equatable {
var url: String {get}
}
func ==<F: Feed>(lhs: F, rhs: F) -> Bool {
return lhs.url == rhs.url
}
protocol Folder {
typealias FeedType
var feeds: [FeedType] {get}
func addFeeds(feedsToAdd: [FeedType])
}
class LocalFeed: Feed {
var url: String
init(url: String) {
self.url = url
}
}
struct AnyFeed: Feed {
var url: String
init<FeedType: Feed>(_ feed: FeedType) {
self.url = feed.url
}
}
class LocalFolder: Folder {
var feeds = [AnyFeed]()
func addFeeds<F: Feed>(feedsToAdd: [F]) {
for f in feedsToAdd {
let oneFeed = AnyFeed(f)
if !feeds.contains(oneFeed) {
feeds += [oneFeed]
}
}
}
}
let localFeed = LocalFeed(url: "example.com")
let folder = LocalFolder()
folder.addFeeds([localFeed])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment