Skip to content

Instantly share code, notes, and snippets.

@rnewman
Created December 19, 2014 19:30
Show Gist options
  • Save rnewman/f60c2d40f3f4467b326b to your computer and use it in GitHub Desktop.
Save rnewman/f60c2d40f3f4467b326b to your computer and use it in GitHub Desktop.
Inherited protocol methods issue
import Foundation
protocol Profile {
func localName() -> String
}
protocol AccountProfile: Profile {
var accountName: String { get }
}
class MockAccountProfile: AccountProfile {
private let name: String = "mockaccount"
init() {
}
func localName() -> String {
return name
}
var accountName: String {
get {
return "[email protected]"
}
}
}
class TestAccountManager {
let loginCallback: (account: AccountProfile) -> ()
init(loginCallback: (account: AccountProfile) -> ()) {
self.loginCallback = loginCallback
}
func login(username: String, password: String) {
let account = MockAccountProfile()
self.loginCallback(account: account)
}
}
// If we do things directly, it works.
let p: Profile = MockAccountProfile()
(p as MockAccountProfile).name
p.localName()
// Inside a callback, dispatch only works if we're explicit about the type.
func loginCallback (profile: Profile) {
profile is MockAccountProfile
(profile as MockAccountProfile).name
(profile as MockAccountProfile).localName()
profile.localName()
}
TestAccountManager(loginCallback: loginCallback).login("foo", password: "bar")
@rnewman
Copy link
Author

rnewman commented Dec 19, 2014

Running this in a Playground yields EXC_BAD_ACCESS on line 50.

@rnewman
Copy link
Author

rnewman commented Dec 19, 2014

Nothing changes if localName is also declared in AccountProfile around line 8, FWIW.

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