我想從我的類中聲明的閉包中引用我的類中的屬性。我無法從閉包中訪問自己,我假設自己會在我的閉包中引用類API。Swift - 使用未解析的標識符'self' - 從類中的閉包
我想聲明一個閉包,我稍後用它作爲參數傳遞給URLSession dataTask(它的工作方式沒有一個錯誤行)。我在標題中列出了錯誤。
使用未解決的標識符「自我」
我已經整整一天寫迅速,現在和我只是想的東西作爲一個沙箱,所以我完全相信一些批評的。
class Api {
struct Location {
var name = String()
var author = String()
var averageRating: String?
var id = Int()
var lat = Double()
var lon = Double()
var type = String()
}
var locations = [Location]()
var doSomething = {(data: Data?, response: URLResponse?, error: Error?) -> Void in
if error != nil {
print(error!.localizedDescription)
} else {
do {
if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any] {
let myResult = json["results"] as! [[String: Any]]
var location : Location! = Location()
for jsonLocation in myResult {
if let name = jsonLocation["name"]{location.name = name as! String}
if let author = jsonLocation["author"]{location.author = author as! String}
if let id = jsonLocation["id"]{location.id = id as! Int}
if let lat = jsonLocation["lat"]{location.lat = lat as! Double}
if let lon = jsonLocation["lon"]{location.lon = lon as! Double}
if let type = jsonLocation["type"]{location.type = type as! String}
//ERROR IS HERE, Why does self not reference class API?
self.locations.append(location)
}
}
} catch {
print("error in JSONSerialization")
}
}
}
}
我發現this,但這個例子是不同的,所以我不知道這是否是同樣的bug或我不理解迅速。
是否有理由使用計算屬性而不是doSomething的函數? – Leon
不,只是我不認爲我需要一個功能。但我可以簡單地使用它。我主要是在試圖學習使用閉包。我明白一個函數是一種閉包,但過去,我不完全知道爲什麼都存在。 – Diesel
是的,所以修復使它成爲一個函數,但我仍然不明白爲什麼函數是一種類型的閉包不起作用。 – Diesel