2016-08-11 31 views
0

在我的代碼中,我在我的類中創建了一個CLLocationManager屬性。 我想使用閉包來初始化位置管理器,因爲我可以在那裏設置委託,並且我認爲在他們的聲明中配置屬性是非常棒的(正如我以前在屬性getter的Objective C中所做的那樣) 。當我使用閉包初始化一個屬性時將自己設置爲委託

所以,我想這一點:

class MapViewController: UIViewController { 
var locationManager: CLLocationManager = { 
    var lm = CLLocationManager() 
    lm.delegate = self 
    return lm 
}() 

extension MapViewController: CLLocationManagerDelegate { 
} 

但是我收到的lm.delegate =自我線以下錯誤。

/Users/.../MapViewController.swift:18:23: '?CLLocationManagerDelegate' 不能指定類型的 值 'NSObject的 - - >()>的MapViewController' 鍵入

MapViewController符合委託(因爲下面的擴展名),所以我不認爲「不確定」是問題。

我可以在viewDidLoad上初始化委託,但是如果可以在屬性本身上進行初始化,我真的很想學會這麼做,因爲它感覺非常整齊。

謝謝!

回答

1

哦,我剛剛找到答案。沒關係。 http://mikebuss.com/2014/06/22/lazy-initialization-swift/

+0

不要忘了,當你能接受它:

lazy var locationManager: CLLocationManager = { [unowned self] in var lm = CLLocationManager() lm.delegate = self return lm }() 

約在斯威夫特延遲初始化這個涼爽的文章邁克 - 巴斯得到它。 –

相關問題