2016-04-18 55 views
0

我有一個函數,其數據我真的很想檢索。檢索函數數據

在括號內,我可以打印出值DecodedData

但是,如果我只是把print(DecodedData)放在函數的外面,Xcode告訴我'預期聲明'如何在整個文件中能夠訪問DecodedData

我試過使用委託方法沒有成功,有沒有其他方式?如果是這樣,我該如何去做呢?

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文件中可用?

+0

你到底在哪裏放了另一個'print(DecodedData)'行 –

+0

緊跟在最後一個大括號之後。 –

+0

這似乎不適合與變量進行交互。你能否複製你班級的孔代碼? –

回答

0

你可以在類中創建靜態變量並使用其他任何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) 
} 
} 

或者您可以創建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)! 
} 
} 
} 

和在其他類中你可以使用單例對象。

+0

謝謝你,先生!你的第一個解決方案就像一個冠軍! –

+0

然後不要忘記接受答案:p – Sahil

+0

哎呀,我差點忘了;) –