检索函数数据

Retrieving Function Data

我有一个函数,我真的很想检索它的数据。

在括号内,我能够打印出值 DecodedData

但是,如果我将 print(DecodedData) 放在函数之外,Xcode 告诉我 'Expected declaration' 我如何才能让 DecodedData 在整个函数中都可以访问文件?

我试过使用delegate方法没有成功,请问还有其他方法吗?如果是这样,我将如何着手去做?

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)
}

我如何让变量 DecodedData 在不同的 Swift 文件中可用?

您可以在 class 中创建静态变量并在任何其他 swift 文件中使用它。

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)
}
}

或者你可以创建你的类的单例对象。

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)!
}
}
}

在其他 class 中,您可以通过单例对象使用。