问题
I have a function whose data I would really like to retrieve.
Within the brackets, I am able to print out the value DecodedData
.
However, if I was to put print(DecodedData)
just outside the function, Xcode tells me that 'Expected declaration' how would I be able to have DecodedData
accessible throughout the file?
I've tried using the delegate method with no success, is there any other way? and if so, how would I go about doing it?
var DecodedData = ""
//Reading Bluetooth Data
func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
if let data = characteristic.value {
DecodedData = String(data: data, encoding: NSUTF8StringEncoding)!
}
print(DecodedData)
}
How would I go about having the variable DecodedData
available throughout different Swift files?
回答1:
you can create static variable in the class and use it any other swift file.
class YourClass {
static var DecodedData: String = ""
...
func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
if let data = characteristic.value {
YourClass.DecodedData = String(data: data, encoding: NSUTF8StringEncoding)!
}
print(YourClass.DecodedData)
}
}
or you can create singleton object of yourclas.
class YourClass {
static let singletonInstance = YourClass()
var DecodedData: String = ""
private init() {
}
func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
if let data = characteristic.value {
self.DecodedData = String(data: data, encoding: NSUTF8StringEncoding)!
}
}
}
and in other class you can use by singleton object.
来源:https://stackoverflow.com/questions/36688478/retrieving-function-data