Retrieving Function Data

 ̄綄美尐妖づ 提交于 2019-12-12 03:29:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!