P5y*_*cH0 5 delegates ios swift
我想在删除之前检查我的removeDelegate方法中是否已有委托.我怎么做?
这是我到目前为止所得到的:
protocol LocationManagerDelegate {
func locationManagerDidUpdateLocation(
oldLocation: CLLocationCoordinate2D,
currentLocation: CLLocationCoordinate2D
)
}
class LocationManager: NSObject {
private var _delegates = [LocationManagerDelegate]()
func removeDelegate(delegate:LocationManagerDelegate) {
if contains(_delegates, delegate) {
// Remove delegate
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,这会在'if contains'行中给出以下错误:
不能使用类型'(@lvalue Array <LocationManagerDelegate>!,LocationManagerDelegate)'的参数列表调用'contains'
Mar*_*n R 12
Swift 3更新:
假设委托实际上是一个类的实例,你可以在协议中要求"继承""class":
protocol LocationManagerDelegate: class {
// ...
}
Run Code Online (Sandbox Code Playgroud)
然后使用该index(where:)方法,使用"indentitiy运算符
===:
class LocationManager: NSObject {
private var _delegates = [LocationManagerDelegate]()
func removeDelegate(delegate:LocationManagerDelegate) {
if let index = _delegates.index(where: { $0 === delegate }) {
_delegates.remove(at: index)
}
}
}
Run Code Online (Sandbox Code Playgroud)
老答案(斯威夫特1):
contains()功能略有不同:
func contains<S : SequenceType where S.Generator.Element : Equatable>(seq: S, x: S.Generator.Element) -> Bool
func contains<S : SequenceType, L : BooleanType>(seq: S, predicate: (S.Generator.Element) -> L) -> Bool
Run Code Online (Sandbox Code Playgroud)
您正在使用第一个,它要求序列元素符合Equatable协议,即可以与它们进行比较==.
假设委托实际上是一个类的实例,你可以在协议中要求"继承""class":
protocol LocationManagerDelegate : class {
// ...
}
Run Code Online (Sandbox Code Playgroud)
然后使用contains()身份运算符的第二个基于谓词的版本===:
func removeDelegate(delegate:LocationManagerDelegate) {
if contains(_delegates, { $0 === delegate }) {
// Remove delegate
}
}
Run Code Online (Sandbox Code Playgroud)
要从数组中删除对象,您必须获取其索引,因此您可以使用/sf/answers/1788015911/中的findIdenticalObject()函数:
func findIdenticalObject<T : AnyObject>(array: [T], value: T) -> Int? {
for (index, elem) in enumerate(array) {
if elem === value {
return index
}
}
return nil
}
Run Code Online (Sandbox Code Playgroud)
然后从数组中查找和删除
func removeDelegate(delegate:LocationManagerDelegate) {
if let index = findIdenticalObject(_delegates, delegate) {
_delegates.removeAtIndex(index)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3071 次 |
| 最近记录: |