Last active
August 29, 2015 14:02
-
-
Save wearhere/965f120a9049a7977599 to your computer and use it in GitHub Desktop.
Separate interfaces and implementations, including private implementations, in Swift.
This file contains 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
import Cocoa | |
class Foo { | |
/// Public interface | |
var message: String? | |
let logMessage: () -> Void | |
init(message: String) { | |
// define a placeholder for `self`, for use within functions in this initializer | |
// in advance of `self` being fully initialized | |
var _self: Foo? | |
/// Private implementation | |
let _name = "Jeff" | |
func name() -> String { | |
return _name | |
} | |
/// Public implementation | |
self.message = message | |
self.logMessage = { () in | |
println("\(name()): \(_self!.message)") | |
} | |
// `self` is fully initialized at this point | |
_self = self | |
} | |
} | |
var foo = Foo(message: "Hi") | |
foo.logMessage() // prints "Jeff: Hi" |
protocol Vehicle {
init(numberOfWheels: Int)
var wheelCount: NSInteger { get }
}
func createTruck(numberOfWheels: Int = 4) -> Vehicle {
class Truck : Vehicle {
var fourWheelDrive: Bool?
init(numberOfWheels: Int) {
fourWheelDrive = true
wheelCount = numberOfWheels
}
var wheelCount: NSInteger
}
return Truck(numberOfWheels: numberOfWheels)
}
var t = createTruck(numberOfWheels: 3)
Has the same subclassing problem mentioned by @wearhere
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I can't figure out how to do subclassing, though. :\
logMessage
can't be overridden by a subclass 'cause it's not a method, and it doesn't seem that it can be changed from within a subclass' initializer.