Reputation: 1861
I am making an app using the CoreBluetooth framework and I recently ported it to swift 2.0. In my code I have a global variable that is a CBCharacteristic, and in swift 1.2 I could just do:
var bob:CBCharacteristic = CBCharacteristic()
But now it gives me the error that the init() function for CBCharacteristic has been explicitly hidden, so I can't initialize it. Is there any way to get around this?
Upvotes: 1
Views: 2333
Reputation: 114846
Instances of CBCharacteristic
can only be retrieved through the service discovery process.
In your Swift 1.2 code you were assigning an 'empty' CBCharacteristic
just to satisfy the compiler regarding uninitialised variables, but you would have had a run-time issue had you tried to use bob
before assigning the 'real' CBCharacteristic
.
Swift is designed to make it easier to produce "safe" code that doesn't have subtle run-time issues from the incorrect use of types. It makes no sense to instantiate an instance of CBCharacteristic
directly and in Swift 2.0 you are actively prevented from doing so.
If your CBCharacteristic
is a property then it should be declared as an optional since it may not have a value until the characteristic is discovered
var bob:CBCharacteristic?
or, if you are sure your code won't attempt to access bob
before it is set -
var bob:CBCharacteristic!
The first will ensure that you write code to unwrap the optional before you use it and the second will give a run-time error if you use it before it is set - both of these are preferable to the potentially difficult to debug problem you would have had simply referencing an 'empty' CBCharacteristic
Upvotes: 5