Last active
August 29, 2015 14:25
-
-
Save ole/a3638f0bc845cbcc2772 to your computer and use it in GitHub Desktop.
Equatable protocols in Swift. A reply to Brent Simmons’s post "Secret Projects Diary #2: Swift 2.0 Protocols" (http://inessential.com/2015/07/19/secret_projects_diary_2_swift_2_0_prot).
This file contains hidden or 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
//: Playground - noun: a place where people can play | |
import Cocoa | |
protocol Feed : Equatable { | |
var url: String {get} | |
} | |
protocol Folder { | |
// This is new: | |
typealias FeedType | |
var feeds: [FeedType] {get} | |
func addFeeds(feedsToAdd: [FeedType]) | |
} | |
func ==<T: Feed>(lhs: T, rhs: T) -> Bool { | |
return lhs.url == rhs.url | |
} | |
class LocalFeed: Feed { | |
var url: String | |
init(url: String) { | |
self.url = url | |
} | |
} | |
class LocalFolder: Folder { | |
// Notice I’m using concrete types (LocalFeed) for the protocol's interface here. | |
// You can't just specify Feed because the compiler must be able to make sure that all | |
// places where the protocol specifies Feed have the same concrete type. | |
var feeds = [LocalFeed]() | |
func addFeeds(feedsToAdd: [LocalFeed]) { | |
for oneFeed in feedsToAdd { | |
if !feeds.contains(oneFeed) { | |
feeds += [oneFeed] | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Edit: I renamed the
typealias Feed
totypealias FeedType
to avoid confusion with theFeed
protocol.