Skip to content

Instantly share code, notes, and snippets.

@callionica
Last active May 5, 2017 16:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save callionica/19da0763c0b0b4c504fc5f46d07e8ee8 to your computer and use it in GitHub Desktop.
Save callionica/19da0763c0b0b4c504fc5f46d07e8ee8 to your computer and use it in GitHub Desktop.
//////////////////////
// File 1
public class Base {
public struct Overridable { // Do not store
private init() {}
}
public struct Protected { // OK to store
private init() {}
}
public struct Secrets {
var message = "Treasure!"
}
private let secrets : Secrets = Secrets()
public func getSecrets(key: Protected)->Secrets {
return secrets
}
public func layout(key: Overridable) {
}
public func updateLayout() {
layout(Overridable())
}
public init(_ proof: (Protected)->()) {
proof(Protected())
}
}
//////////////////////
// File 2
class Derived : Base {
private var key : Protected? = nil
init() {
var key : Protected?
super.init({ k in key = k })
self.key = key!
}
func callSecrets() {
print(getSecrets(key!).message)
}
override func layout(key: Overridable) {
super.layout(key) // Can call the base class
}
}
var derived = Derived()
derived.callSecrets()
@callionica
Copy link
Author

callionica commented May 29, 2016

Swift doesn't provide "protected" as an access level, but you can emulate it. And you can distinguish between methods that are supposed to be called and those that are only supposed to be overridden.

Write up at https://www.callionica.com/developer/#swift-protected

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