Skip to content

Instantly share code, notes, and snippets.

@wearhere
Last active August 29, 2015 14:02
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 wearhere/965f120a9049a7977599 to your computer and use it in GitHub Desktop.
Save wearhere/965f120a9049a7977599 to your computer and use it in GitHub Desktop.
Separate interfaces and implementations, including private implementations, in Swift.
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"
@wearhere
Copy link
Author

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.

@derrh
Copy link

derrh commented Jun 11, 2014

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)

@derrh
Copy link

derrh commented Jun 11, 2014

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