need self to set all constants of a swift class in init need self to set all constants of a swift class in init swift swift

need self to set all constants of a swift class in init


UPDATE for Swift 1.2 and later

Unfortunately, it doesn’t seem to be possible any more to have bluetoothManager as a constant. Starting from Swift 1.2, in an initializer, constant properties can only assign a value once. This doesn’t allow us to start with a nil value by declaring it as an optional and change it later in the initialization process. Here’s the updated version with bluetoothManager as a variable.

class Broadcaster: NSObject, CBPeripheralManagerDelegate {    let broadcastID: NSUUID    var bluetoothManager: CBPeripheralManager!    init(broadcastID: NSUUID) {        self.broadcastID = broadcastID        super.init()        let options: Dictionary<String, AnyObject> = [ CBPeripheralManagerOptionShowPowerAlertKey: true ]        self.bluetoothManager = CBPeripheralManager(delegate: self, queue: nil, options: options)    }}

Original answer

You could use implicitly unwrapped optional here (for bluetoothManager) and assign the value to it after super.init():

class Broadcaster: NSObject, CBPeripheralManagerDelegate {    let broadcastID: NSUUID    let bluetoothManager: CBPeripheralManager!    init(broadcastID: NSUUID) {        self.broadcastID = broadcastID        super.init()        let options: Dictionary<NSString, AnyObject> = [ CBPeripheralManagerOptionShowPowerAlertKey: true ]        self.bluetoothManager = CBPeripheralManager(delegate: self, queue: nil, options: options)    }}

Because bluetoothManager is an optional, by the time super.init() is called, all properties are initialized (bluetoothManager is implicitly initialized with nil). But because we know that bluetoothManager will definitely have the value after the class is initialized, we declare it as explicitly unwrapped to avoid checks when using it.

UPDATE

A property can be declared as constant and still be changed in the initializer. One just has to make sure it has a definite value by the time initialization finishes. This is documented in chapter “Modifying Constant Properties During Initialization” of Swift book.

The situation when a property needs to be initialized with a call where self must be passed from not yet fully initialized object is described in chapter “Unowned References and Implicitly Unwrapped Optional Properties.”


How about setting up your bluetoothManager as a @lazy property and accessing it later on e.g. to startAdvertising?

@lazy var bluetoothManager: CBPeripheralManager = CBPeripheralManager(delegate: self, queue: nil)init() { ... }func start() {    self.bluetoothManager.startAdvertising([ "foo" : "bar" ])}