gpt4 book ai didi

iOS swift : Array of Objects conforming to a Protocol: How to check if array contains

转载 作者:行者123 更新时间:2023-11-29 02:27:53 28 4
gpt4 key购买 nike

我正在尝试实现一个图像下载器类。这是一个单例实现。这个想法是要求实例下载图像并注册为该图像下载的观察者。到目前为止,这是我想出的:

public protocol ImageDownloaderDelegate {
func imageDownloadFinished(success: Bool)
}

public class ImageDownloader {
var list: [Int64] = []
var observer: [Int64:[ImageDownloaderDelegate]] = [:]
var downloading: Bool = false

public func downloadImageWithId(immutableId: Int64, delegate: ImageDownloaderDelegate) {
// Add Id to download list
if (!contains(list, immutableId)) {
list.append(immutableId)
}

// Add Observer
var observerList = observer[immutableId]
if (observerList == nil) {
observerList = [delegate]
} else if (!contains(observerList, delegate)) {
observerList!.append(delegate)
}
observer[immutableId] = observerList

// Start to download
if (!downloading) {
self.downloadNextImage()
}
}

private func downloadNextImage() {
...
}

/// A shared instance of the class
public class var defaultImageDownloader: ImageDownloader {
struct Singleton {
static let instance = ImageDownloader()
}
return Singleton.instance
}
}

我收到以下错误:

“ImageDownloaderDelegate”不能转换为“S.Generator.Element -> L”

非常感谢任何帮助

最佳答案

您没有将正确的参数传递给 contains 函数,该函数需要一个集合和一个谓词(闭包)。

你需要做的

public protocol ImageDownloaderDelegate : class {
func imageDownloadFinished(success: Bool)
}

public class ImageDownloader {
var list: [Int64] = []
var observer: [Int64:[ImageDownloaderDelegate]] = [:]
var downloading: Bool = false

public func downloadImageWithId(immutableId: Int64, delegate: ImageDownloaderDelegate) {
// Add Id to download list
if (!contains(list, immutableId)) {
list.append(immutableId)
}

// Add Observer
var observerList = observer[immutableId]
if (observerList == nil) {
observerList = [delegate]
} else if !contains(observerList!, { observer in observer === delegate }) {
observerList!.append(delegate)
}
observer[immutableId] = observerList

// Start to download
if (!downloading) {
self.downloadNextImage()
}
}

private func downloadNextImage() {
...
}

/// A shared instance of the class
public class var defaultImageDownloader: ImageDownloader {
struct Singleton {
static let instance = ImageDownloader()
}
return Singleton.instance
}
}

关于iOS swift : Array of Objects conforming to a Protocol: How to check if array contains,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27282451/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com