是什麼傳遞[weak self]
作爲參數,以將閉合VS傳遞[weak self]()
差()
例如之間的差:
dispatch_async(dispatch_get_main_queue()) { [weak self] in
//Some code here
}
V/S
dispatch_async(dispatch_get_main_queue()) { [weak self]() -> Void in
//Some code here
}
是什麼傳遞[weak self]
作爲參數,以將閉合VS傳遞[weak self]()
差()
例如之間的差:
dispatch_async(dispatch_get_main_queue()) { [weak self] in
//Some code here
}
V/S
dispatch_async(dispatch_get_main_queue()) { [weak self]() -> Void in
//Some code here
}
您不會將[weak self]()
作爲參數傳遞給閉包。
[weak self]
是捕獲列表和先於() -> Void
在封閉的表達。
的返回類型或兩者的參數列表並返回,如果他們能 從上下文來推斷類型可以省略,因此,所有這些都是有效的 ,完全等同:
dispatch_async(dispatch_get_main_queue()) { [weak self]() -> Void in
self?.doSomething()
}
dispatch_async(dispatch_get_main_queue()) { [weak self]() in
self?.doSomething()
}
dispatch_async(dispatch_get_main_queue()) { [weak self] in
self?.doSomething()
}
閉合需要一個空參數列表()
並具有Void
返回類型。
@MartinR更新後的代碼。實際上,在一些實現中,我看到[weak self]沒有使用圓括號,有些我認爲它被用作[weak self]()。這兩者之間的區別究竟是什麼? –